<?php

namespace app\api\controller\v1;

use think\Controller;
use think\Request;
use app\api\controller\Api;
use think\Response;
use app\api\controller\UnauthorizedException;
use think\Db;
use think\Validate;
use think\Image;
use JPush\Client as JPush;


/**
 * 所有资源类接都必须继承基类控制器
 * 基类控制器提供了基础的验证，包含app_token,请求时间，请求是否合法的一系列的验证
 * 在所有子类中可以调用$this->clientInfo对象访问请求客户端信息，返回为一个数组
 * 在具体资源方法中，不需要再依赖注入，直接调用$this->request返回为请具体信息的一个对象
 * date:2017-07-25
 */
class Users extends Api
{
    /**
     * 允许访问的方式列表，资源数组如果没有对应的方式列表，请不要把该方法写上，如user这个资源，客户端没有delete操作
     */
    public $restMethodList = 'get|post|put';

    /**
     * restful没有任何参数
     *
     * @return \think\Response
     */
    public function index()
    {
         return 'index';
        
    }

    /**
     * post方式
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save()
    {
        echo "save";
        dump($this->request);
        dump($this->clientInfo);
    }

//   im test
    public function iim($user_id){
        $result = db('user_info')->field('user_name,small_user_icon')->where(['user_id' => $user_id])->select();
        if(!empty($result)){return $this->returnmsg(200,'传递成功',$result);
        }else{
            return $this->returnmsg(404,'not found this user');
        }
    }



     public function read($user_id)
    {   
        
        $userInfo_data = Db::query("select * from user_info where user_id = '$user_id'");
        // $pet_data = Db::query("select * from ym_pet where pet_id = '$pet_id'");
        // 条件错误
        $pet_data = Db::query("select * from ym_pet where user_id = '$user_id'");
        $pet_image = Db::query("select img from pet_image where user_id = '$user_id'");
        
        
        if (!empty($userInfo_data) && !empty($pet_data) && !empty($pet_data)) {
            // var_dump($data);
            $num = count($pet_image);
            $key_name = array();
            for ($num; $num > 0 ; $num--) { 
                array_push($key_name,$num);
            }
            // $key_name = array('1','2','3','4');
            $pet_image = array_combine($key_name,array_values($pet_image));
            // $pet_image = array_combine($keys, array_values($pet_image));

            return $this->returnmsg(200,'read success',$userInfo_data,$pet_data,$pet_image);
        }else{
            return $this->returnmsg(404,'not found this user');
        }
    }


    /**
     * PUT方式
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update()
    {
        return 'update';
    }

    /**
     * delete方式
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete()
    {
        return 'delete';
    }

    //推送全部
    public function push($user_id,$message){
        $appkey = 'a3d1bad973276db7cee3f40a';
        $master_secret = 'ac5c6c6b1101643082c88913';
        $client = new JPush($appkey,$master_secret);
        $r_id = Db::query("select registration_id from ym_device_no where user_id = '$user_id'");
        $registration_id = $r_id[0]['registration_id'];
        
        $push = $client->push();
        $push->setPlatform('all');
        //别名
        $push->addAlias($user_id);
        //设备号
        $push->addRegistrationId($registration_id);
        // $push->iosNotification();
        $push->iosNotification($message, [
              'sound' => 'sound.cat',
              'badge' => '+1',
              
        ]);
        $push->options(array(
              "apns_production" => true 
              )); 
        // try {
        $push->send(); 
        
    }

    // 发送自定义消息
    public function custom_message($user_id,$message){
        $appkey = 'a3d1bad973276db7cee3f40a';
        $master_secret = 'ac5c6c6b1101643082c88913';
        $client = new JPush($appkey,$master_secret);
        $r_id = Db::query("select registration_id from ym_device_no where user_id = '$user_id'");
        $registration_id = $r_id[0]['registration_id'];
        $payload = $client->push()
            ->setPlatform('all')
            ->addAlias($user_id)
            //设备号
            ->addRegistrationId($registration_id)
            ->message($message, [
              'title' => 'Tix',
              'content_type' => 'text',
              'extras' => [
               'logout' => '1'
              ]
            ])
            ->options(array(
              "apns_production" => true  //true表示发送到生产环境(默认值)，false为开发环境
            ));

            // try {
            $response = $payload->send(); // 执行推送
        }

    //消息
    public function show_message($user_id,$pageno){
        
        $pagesize = 10;
        $startno = $pageno *$pagesize;
        $arr = [];
        $result = Db::query("select user_id,m_id from ym_message 
                            where be_user_id = '$user_id' 
                            order by create_time 
                            desc limit {$startno},{$pagesize}");
        $length = count($result);
        for ($i=0; $i < $length; $i++) { 
            $m_id = $result[$i]['m_id'];
            // 关注
            $follow = Db::query("select c.user_name,c.user_icon,b.m_id,b.user_id,b.message_type,b.create_time 
                                    from ym_message_follow as a 
                                    join ym_message as b on a.m_id = b.m_id 
                                    join user_info as c on a.user_id = c.user_id 
                                    where a.m_id = '$m_id'");
            if (!empty($follow)) {
                //判断是否互相关注
                $follow_id = $result[$i]['user_id'];
                $follow_or_not = Db::table('ym_user_follow')->where('user_id',$user_id)->where('follow_id',$follow_id)->select();
                if (!empty($follow_or_not)) {
                    $follow[0]['follow_status'] = 1;//你也关注了对方
                }else{
                    $follow[0]['follow_status'] = 0;//你还没关注对方
                }
                $arr [] = $follow[0];
            }

            // 点赞
            $upvote = Db::query("select c.user_name,c.user_icon,a.module_type,a.id as ID,a.cmmt_id,a.img_url,b.m_id,b.user_id,b.message_type,b.create_time 
                                from ym_message_upvote as a 
                                join ym_message as b on a.m_id = b.m_id 
                                join user_info as c on b.user_id = c.user_id 
                                where a.m_id = '$m_id'");
            if (!empty($upvote)) {
                $arr [] = $upvote[0];
            }
            // 评论
            $cmmt =  Db::query("select c.user_name,c.user_icon,a.module_type,a.id as ID,a.cmmt_id,a.content,a.img_url,b.m_id,b.user_id,b.message_type,b.create_time 
                                from ym_message_cmmt as a 
                                join ym_message as b on a.m_id = b.m_id 
                                join user_info as c on b.user_id = c.user_id 
                                where a.m_id = '$m_id'");
            if (!empty($cmmt)) {
                $arr [] = $cmmt[0];
            }
            //回复 
            $reply =  Db::query("select c.user_name,c.user_icon,a.module_type,a.id as ID,a.cmmt_id,a.cmmt_content,a.img_url,b.m_id,b.user_id,b.message_type,b.create_time 
                                from ym_message_reply as a 
                                join ym_message as b on a.m_id = b.m_id 
                                join user_info as c on b.user_id = c.user_id 
                                where a.m_id = '$m_id'");
            if (!empty($reply)) {
                $arr [] = $reply[0];
            }
            // 打赏
            $reward =  Db::query("select c.user_name,c.user_icon,a.module_type,a.id as ID,a.food_count,a.img_url,b.m_id,b.user_id,b.message_type,b.create_time from ym_message_reward as a join ym_message as b on a.m_id = b.m_id join user_info as c on b.user_id = c.user_id where a.m_id = '$m_id'");
            if (!empty($reward)) {
                $arr [] = $reward[0];
            }
            // 预约
            $appointment =  Db::query("select c.user_name,c.user_icon,a.appointment_id,b.m_id,b.user_id,b.message_type,b.create_time 
                from ym_message_appointment as a 
                join ym_message as b on a.m_id = b.m_id 
                join user_info as c on b.user_id = c.user_id 
                where a.m_id = '$m_id'");
            if (!empty($appointment)) {
                $arr [] = $appointment[0];
            }
            // 预约回复
            $appointment_agree = Db::query("select c.user_name,c.user_icon,d.mobilephone,a.appointment_id,a.refuse_reason,b.m_id,b.user_id,b.message_type,b.create_time 
                from ym_message_appointment_agree_or_not as a 
                join ym_message as b on a.m_id = b.m_id 
                join user_info as c on b.user_id = c.user_id 
                join ym_user as d on b.user_id = d.id 
                where a.m_id = '$m_id'");           
            if (!empty($appointment_agree)) {
                if (empty($appointment_agree[0]['refuse_reason'])) {
                    $appointment_agree[0]['is_agree'] = 1;
                }else{
                    $appointment_agree[0]['is_agree'] = 0;
                }
                $arr [] = $appointment_agree[0];
            }
            // 寄养
            $fosterage =  Db::query("select c.user_name,c.user_icon,a.fosterage_id,b.m_id,b.user_id,b.message_type,b.create_time 
                from ym_message_fosterage as a 
                join ym_message as b on a.m_id = b.m_id 
                join user_info as c on b.user_id = c.user_id 
                where a.m_id = '$m_id'");
            if (!empty($fosterage)) {
                $arr [] = $fosterage[0];
            }
            // 寄养回复
            $fosterage_agree = Db::query("select c.user_name,c.user_icon,d.mobilephone,a.fosterage_id,a.refuse_reason,b.m_id,b.user_id,b.message_type,b.create_time from ym_message_fosterage_agree_or_not as a join ym_message as b on a.m_id = b.m_id join user_info as c on b.user_id = c.user_id join ym_user as d on b.user_id = d.id where a.m_id = '$m_id'");
            if (!empty($fosterage_agree)) {
                if (empty($fosterage_agree[0]['refuse_reason'])) {
                    $fosterage_agree[0]['is_agree'] = 1;
                }else{
                    $fosterage_agree[0]['is_agree'] = 0;
                }
                $arr [] = $fosterage_agree[0];
            }

        }
        return $this->returnmsg(200,'message',$arr);
    }

    //上传头像
    public function change_user_icon($user_id)
    {
        if($this->request->isPost()){
                // 获取上传文件
                $files = Request::instance()->file('user_icon');
                // 移动到框架应用根目录/public/uploads/ 目录下
                // $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
                $info = $files->move(ROOT_PATH . 'public' . DS. 'uploads'.DS.'icon');
                //$res = db('user')->where('user_id', $data['user_id'])->setField('user_icon', $head_img_path);
                if($info){
                    // 成功上传后 获取上传信息
                    // 输出 jpg
                    $path = '/uploads/icon/' . $info->getSaveName();
                    $path = str_replace('\\', '/', $path);
                    // $icon_path = str_replace('\\', '/', $path);
                    $res = Db::query("update user_info set user_icon = '$path' where user_id = '$user_id'");
                    // $image
                    $image = Image::open(request()->file('user_icon'));
                    // 按照原图的比例生成一个最大为150*150的缩略图并保存为thumb.png
                    $image->thumb(105, 105, Image::THUMB_CENTER)->save(ROOT_PATH . 'public' . $path);


               if (empty($res)) {
                      return  $this->returnmsg(200, '头像上传成功!', 'icon_url: '.$path);
                    } else {
                      return  $this->returnmsg(400, '上传头像失败!');
                    }
                }else{
                // 上传失败获取错误信息
                echo $file->getError();
                } 
        }
    }
    //增加宠物图片(发照片)
    public function upload_petImg($pet_id,$user_id,$text)
    {
               // 获取上传文件
                $files = Request::instance()->file('img');
                // 移动到框架应用根目录/public/uploads/ 目录下
                // $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
                $info = $files->move(ROOT_PATH . 'public' . DS. 'uploads'.DS.'images');
                //$res = db('user')->where('user_id', $data['user_id'])->setField('user_icon', $head_img_path);
                if($info){
                $path = '/uploads/images/' . $info->getSaveName();
                $path = str_replace('\\', '/', $path);
                if (empty($text)) {
                    $res = Db::query("insert into pet_image values(null,'$pet_id','$user_id','','$path')");
                }else{
                    $res = Db::query("insert into pet_image values(null,'$pet_id','$user_id','$text','$path')");
                }
                // $image = Image::open(request()->file('user_icon'));
                // // 按照原图的比例生成一个最大为200*200的缩略图并保存为thumb.png
                // $image->thumb(200, 200, Image::THUMB_CENTER)->save(ROOT_PATH . 'public' . $path);
               if (empty($res)) {
                      return  $this->returnmsg(200, '图片上传成功!', 'image_url: '.$path);
                    } else {
                      return  $this->returnmsg(400, '图片上传失败!');
                    }
                }else{
                // 上传失败获取错误信息
                echo $file->getError(); 
        } 
    }
    
    //上传用户资料
    public function userInfo_upload($user_id,$user_name,$user_gender,$user_age,$pet_type,$user_type)
    {
        switch ($user_gender) {
            case '男':
                $user_gender = 0;
                break;
            case '女':
                $user_gender = 1;
                break;
            case '保密':
                $user_gender = 2;
                break;
        }

        switch ($pet_type) {
            case '狗':
                $pet_type = 0;
                break;
            case '猫':
                $pet_type = 1;
                break;
            case '两者都是':
                $pet_type = 2;
                break;
            case '其它':
                $pet_type = 3;
                break;
        }

        switch ($user_type) {
            case '吸宠者':
                $user_type = 0;
                break;
            case '铲屎官':
                $user_type = 1;
                break;
        }

        $result = Db::query("select user_name from user_info where user_id = '$user_id' ");

        if (!empty($result)) {
            return $this->returnmsg(401,'Fail,User name exist');
        }else{
            // 获取上传文件
            $files = Request::instance()->file('user_icon');
            
            // 移动到框架应用根目录/public/uploads/ 目录下
            // $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
            $info = $files->move(ROOT_PATH . 'public' . DS. 'uploads'.DS.'icon');
            //$res = db('user')->where('user_id', $data['user_id'])->setField('user_icon', $head_img_path);
            if($info){
                // 成功上传后 获取上传信息
                // 输出 jpg
                $path = '/uploads/icon/' . $info->getSaveName();
                $photo = $info->getFilename();
                $small_path = ROOT_PATH . 'public' . DS. 'uploads'.DS.'small_user_icon'.DS.$photo;
                //原大图路径,当时我获取的时候费了不少时间  .DS.date("m-d")
                // $small_path = 'https://cloudpetor.com/api/public/uploads/small_user_icon'.DS.$photo;
                $path = str_replace('\\', '/', $path);
                $small_path = str_replace('\\', '/', $small_path);
                // $image
                $image = Image::open(request()->file('user_icon'));
                // 按照原图的比例生成一个最大为72*72的缩略图并保存为thumb.png
                $image->thumb(72, 72, Image::THUMB_CENTER)->save($small_path);
               
                $follow_count = Db::table('ym_user_follow')->where('user_id',$user_id)->count('user_id');
                $fans_count = Db::table('ym_user_follow')->where('follow_id',$user_id)->count('follow_id');

                $len = strlen(ROOT_PATH. 'public');

                $small_path = substr_replace($small_path,'',0,$len);
                
                Db::query("insert into user_info values('$user_id','$user_name','$user_gender','$user_age',default,'$user_type','$follow_count','$fans_count','$pet_type',default,'$path','$small_path',default,default)");
                
                return $this->returnmsg(200,"用户资料添加成功");
            }
        }  
    }

    //上传宠物信息
    public function petinfo_upload($user_id,$pet_name,$pet_gender,$pet_brith,$pet_kind){
        switch ($pet_gender) {
            case '男':
                $pet_gender = 0;
                break;
            case '女':
                $pet_gender = 1;
                break;
        }

        $files = Request::instance()->file('img_url');
        $file = Request::instance()->file('pet_icon');
        // 移动到框架应用根目录/public/uploads/ 目录下
        // $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
        $info = $files->move(ROOT_PATH . 'public' . DS. 'uploads'.DS.'pet_img');
        $info_icon = $file->move(ROOT_PATH . 'public' . DS. 'uploads'.DS.'pet_icon');
        //$res = db('user')->where('user_id', $data['user_id'])->setField('user_icon', $head_img_path);
        if($info && $info_icon){
            // 成功上传后 获取上传信息
            // 输出 jpg
            $path = '/uploads/pet_img/' . $info->getSaveName();
            $icon_path = '/uploads/pet_icon/' . $info_icon->getSaveName();

            $photo = $info_icon->getFilename();
            $small_path = ROOT_PATH . 'public' . DS. 'uploads'.DS.'small_pet_icon'.DS.$photo;

            $path = str_replace('\\', '/', $path);
            $icon_path = str_replace('\\', '/', $icon_path);
            $small_path = str_replace('\\', '/', $small_path);

            // $image
            $image = Image::open(request()->file('pet_icon'));
            // 按照原图的比例生成一个最大为72*72的缩略图并保存为thumb.png
            $image->thumb(72, 72, Image::THUMB_CENTER)->save($small_path);

            $len = strlen(ROOT_PATH. 'public');

            $small_path = substr_replace($small_path,'',0,$len);
            $data = ['user_id'=>$user_id,'pet_name'=>$pet_name,'pet_gender'=>$pet_gender,'pet_brith'=>$pet_brith,'pet_kind'=>$pet_kind,'pet_icon'=>$icon_path,'small_pet_icon'=>$small_path,'img_url'=>$path];
            $pet_id = Db::table('ym_pet')->insertGetId($data);
            
            Db::query("insert into ym_pet_hungry values(null,'$pet_id',default,default,default,default)");
            return $this->returnmsg(200,"添加宠物信息成功,请等待审核");
        }
    }

    //喂养
    public function pet_hungry_level($user_id,$be_user_id,$pet_id,$food_count){
        
            $time = date('Y-m-d H:i:s');
            $food = Db::query("select pet_food from ym_pet_food where user_id = '$user_id'");
            $pet_food = $food[0]['pet_food'];
            if ($pet_food < $food_count) {
                return $this->returnmsg(402,'宠粮余额不足,请充值');
            }else{
                $hungry = Db::query("select pet_hungry_level 
                                    from ym_pet_hungry 
                                    where pet_id = '$pet_id'");
                $hungry_level = $hungry[0]['pet_hungry_level'];
                
                Db::query("update ym_pet_hungry set pet_hungry_level = '$hungry_level' + '$food_count' where pet_id = '$pet_id'");
                Db::query("update ym_pet_food set pet_food = '$pet_food' - '$food_count' where user_id = '$user_id'");
                $be_food = Db::query("select pet_food from ym_pet_food where user_id = '$be_user_id'");
                $be_pet_food = $be_food[0]['pet_food'];
                Db::query("update ym_pet_food set pet_food = '$be_pet_food' + '$food_count' where user_id = '$be_user_id'");

                 // message
                $message_data = ['be_user_id'=>$be_user_id,'user_id'=>$user_id,'message_type'=>9,'create_time'=>$time];
                $m_id = Db::table('ym_message')->insertGetId($message_data);
                $img = Db::query("select pet_icon from ym_pet where pet_id = '$pet_id' limit 1");
                $img_url = $img[0]['pet_icon'];
                $reward_data = ['m_id'=>$m_id,'module_type'=>2,'id'=>$pet_id,'food_count'=>$food_count,'img_url'=>$img_url];
                $m_reward_id = Db::table('ym_message_reward')->insertGetId($reward_data);
                $user_name = Db::query("select user_name from user_info where user_id = '$user_id'");
                $name = $user_name[0]['user_name'];

                //推送
                $be_user_id = strval($be_user_id);
                $this->push($be_user_id,$name.'喂养了你的宠物'.$food_count.'克宠粮');
                return $this->returnmsg(200,'喂养成功');
            }
    }

    //定时减去百分之四十饥饿值11-29
    public function less_hungry_level(){
        $result = Db::query("select pet_hungry_level from ym_pet_hungry");
        $length = count($result);
        for ($i=0; $i < $length ; $i++) { 
            // $pet_hungry_level = ;
            Db::query("update ym_pet_hungry set pet_hungry_level = '".$result[$i]['pet_hungry_level']."' *0.6 where pet_hungry_level = '".$result[$i]['pet_hungry_level']."' ");
        }
        return $this->returnmsg(200,'饥饿值已经减去40%');
    }

    //判断用户类型
    public function judgement_user_type($user_id){
        $result = Db::query("select user_type from user_info where user_id = '$user_id'");
        if ($result[0]['user_type'] = 0) {
            return $this->returnmsg(200,"吸宠者");
        }else{
            return $this->returnmsg(200,"铲屎官");
        }
    }

    //判断是否经过宠物认证
    public function permisstion_to_access($pet_id){
        $result = Db::query("select permisstion_to_access from ym_pet where pet_id = '$pet_id'");
        if ($result[0]['permisstion_to_access'] == 1) {
            return $this->returnmsg(200,'认证通过');
        }else{
            return $this->returnmsg(401,'您还没有认证宠物信息哦，快去填写信息吧');
        }
    }

    //关注&取消关注
    public function user_follow($user_id,$follow_id){
        $follow_time = date("Y-m-d H:i:s");
        if ($user_id == $follow_id) {
            return $this->returnmsg(401,'不能自己关注自己的哦');
        }else{
            $result = Db::query("select *from ym_user_follow where user_id = '$user_id' and follow_id = '$follow_id'");
            if (!empty($result)) {//已经关注
                //取消关注
                Db::table('ym_user_follow')->where('user_id',$user_id)->where('follow_id',$follow_id)->delete();
                $follow = Db::query("select follow_count from user_info where user_id = '$user_id'");
                $follow_count = $follow[0]['follow_count'];
                $fans = Db::query("select fans_count from user_info where user_id = '$follow_id'");
                $fans_count = $fans[0]['fans_count'];
                if ($follow_count != 0 && $follow_count >0) {
                    Db::query("update user_info set follow_count = '$follow_count' - 1 where user_id = '$user_id'");
                }
                if ($fans_count != 0 && $fans_count >0) {
                    Db::query("update user_info set fans_count = '$fans_count' - 1 where user_id = '$follow_id'");
                }
                
                // Db::query("update user_info set follow_count = '$follow_count' - 1 where user_id = '$user_id'");
                // Db::query("update user_info set fans_count = '$fans_count' - 1 where user_id = '$follow_id'");
                return $this->returnmsg(200,'取消关注成功');
            }else{//未关注
                //关注
                $data = ['user_id'=>$user_id,'follow_id'=>$follow_id,'follow_time'=>$follow_time];
                Db::table('ym_user_follow')->insert($data);

                //插入消息表
                $message_data = ['be_user_id'=>$follow_id,'user_id'=>$user_id,'message_type'=>0,'create_time'=>$follow_time];
                $m_id = Db::table('ym_message')->insertGetId($message_data);
                Db::query("insert into ym_message_follow values(null,'$m_id','$follow_id','$user_id')");

                $follow = Db::query("select follow_count from user_info where user_id = '$user_id'");
                $follow_count = $follow[0]['follow_count'];
                $fans = Db::query("select fans_count from user_info where user_id = '$follow_id'");
                $fans_count = $fans[0]['fans_count'];
                Db::query("update user_info set follow_count = '$follow_count' + 1 where user_id = '$user_id'");
                Db::query("update user_info set fans_count = '$fans_count' + 1 where user_id = '$follow_id'");

                $user_name = Db::query("select user_name from user_info where user_id = '$user_id'");
                $name = $user_name[0]['user_name'];
                // $message = '关注了你';
                $this->push($follow_id,$name.'关注了你');
                return $this->returnmsg(200,'关注成功');
            }
        }
    }

    //用户关注的人
    public function show_follows($user_id,$other_user_id,$pageno){
        $pagesize = 10;
        $startno = $pageno*$pagesize;
        $arr = [];
        $follow_user_id = Db::table('ym_user_follow')->field('follow_id')->where('user_id',$other_user_id)->limit($startno,$pagesize)->select();
        $length = count($follow_user_id);
        // echo $length;
        for ($i=0; $i < $length; $i++) { 
            $follow_id = $follow_user_id[$i]['follow_id'];
            $follow_or_not = Db::table('ym_user_follow')->where('user_id',$user_id)->where('follow_id',$follow_id)->select();
            $follow_user = Db::table('user_info')->field(['user_id','user_name','user_icon','user_desc'])->where('user_id',$follow_id)->select();
            if (!empty($follow_or_not)) {
                $follow_user[0]['follow_status'] = 1;
            }else{
                $follow_user[0]['follow_status'] = 0;
            }
            $arr[] = $follow_user[0];
        }
        return $this->returnmsg(200,'关注的人',$arr); 
    }

    //被关注(粉丝)
    public function show_fans($user_id,$other_user_id,$pageno){
        $pagesize = 10;
        $startno = $pageno*$pagesize;
        $arr = [];
        $fans_user_id = Db::table('ym_user_follow')->field('user_id')->where('follow_id',$other_user_id)->limit($startno,$pagesize)->select();
        // $follow_or_not = Db::table('ym_user_follow')->field('follow_or_not')->where('follow_id',$user_id)->select();
        $length = count($fans_user_id);
        for ($i=0; $i < $length; $i++) { 
            $fans_id = $fans_user_id[$i]['user_id'];

            $follow_or_not = Db::table('ym_user_follow')->where('user_id',$user_id)->where('follow_id',$fans_id)->select();
            // var_dump($follow_or_not);
            $fans_user = Db::table('user_info')->alias('a')->join('ym_user_follow b','a.user_id = b.user_id')->field(['a.user_id','a.user_name','a.user_icon','a.user_desc'])->where('a.user_id',$fans_id)->where('b.follow_id',$other_user_id)->select();
            
            if (!empty($follow_or_not)) {
                $fans_user[0]['follow_status'] = 1;
            }else{
                $fans_user[0]['follow_status'] = 0;
            }

            $arr[] = $fans_user[0];
        }

        return $this->returnmsg(200,'粉丝',$arr);
    }

    public function show_userinfo($user_id){
        $result = Db::query("select *from user_info where user_id = '$user_id'");
        $name = Db::query("select user_name from user_info where user_id = '$user_id'");
        $user_name = $name[0]['user_name'];
        return $this->returnmsg(200,'个人信息',$result);
    }

    public function edit_user_info($user_id){
        $result = Db::query("select user_name,user_gender,user_age,user_desc,user_type,user_icon,background_img from user_info where user_id = '$user_id'");

        return $this->returnmsg(200,'用户资料',$result);
    }

    public function change_userinfo($user_id,$user_name,$user_gender,$user_age,$user_desc,$user_type){
        switch ($user_gender) {
            case '男':
                $user_gender = 0;
                break;
            case '女':
                $user_gender = 1;
                break;
            case '保密':
                $user_gender = 2;
                break;
        }
        switch ($user_type) {
            case '吸宠者':
                $user_type = 0;
                break;
            case '铲屎官':
                $user_type = 1;
                break;
        }

        $file = Request::instance()->file('user_icon');
        if ($file) {
        
            $info = $file->move(ROOT_PATH . 'public' . DS. 'uploads'.DS.'icon');
            if ($info) {
                $path = '/uploads/icon/' . $info->getSaveName();
                $photo = $info->getFilename();
                $small_path = ROOT_PATH . 'public' . DS. 'uploads'.DS.'small_user_icon'.DS.$photo;
                //原大图路径,当时我获取的时候费了不少时间  .DS.date("m-d")
                // $small_path = 'https://cloudpetor.com/api/public/uploads/small_user_icon'.DS.$photo;
                $path = str_replace('\\', '/', $path);
                $small_path = str_replace('\\', '/', $small_path);
                // $image
                $image = Image::open(request()->file('user_icon'));
                // 按照原图的比例生成一个最大为72*72的缩略图并保存为thumb.png
                $image->thumb(72, 72, Image::THUMB_CENTER)->save($small_path);

                $len = strlen(ROOT_PATH. 'public');

                $small_path = substr_replace($small_path,'',0,$len);
                
                Db::query("update user_info set user_name = '$user_name',user_gender = '$user_gender',user_age = '$user_age',user_type = '$user_type',user_desc = '$user_desc',user_icon = '$path',small_user_icon = '$small_path' where user_id = '$user_id'");
                $this->change_background_img($user_id);
            }
        }else{
            Db::query("update user_info set user_name = '$user_name',user_gender = '$user_gender',user_age = '$user_age',user_type = '$user_type',user_desc = '$user_desc' where user_id = '$user_id'");
            $this->change_background_img($user_id);
        }
        return $this->returnmsg(200,"资料修改成功");
    }

    //修改用户背景图片
    public function change_background_img($user_id){
        // 获取上传文件
        $files = Request::instance()->file('background_img');
        // 移动到框架应用根目录/public/uploads/ 目录下
        // $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
        if (!empty($files)) {
            $info = $files->move(ROOT_PATH . 'public' . DS. 'uploads'.DS.'background_img');
            //$res = db('user')->where('user_id', $data['user_id'])->setField('user_icon', $head_img_path);
            if($info){
                // 成功上传后 获取上传信息
                // 输出 jpg
                $path = '/uploads/background_img/' . $info->getSaveName();
                $path = str_replace('\\', '/', $path);
                Db::query("update user_info set background_img = '$path' where user_id = '$user_id'");
            }
        }
    }

    //修改密码
    public function change_psw($user_id,$password,$confirm_password,$new_password){
        $psw = Db::query("select password from ym_user where id = '$user_id'");
        if (md5($password) == $psw[0]['password'] ) {
            // $new_password = md5($new_password);
            if ($new_password == $confirm_password) {
                Db::query("update ym_user set password = 'md5($new_password)' where id = '$user_id'");
                return $this->returnmsg(200,"修改密码成功");
            }else{
                return $this->returnmsg(401,"两次输入密码不一致");
            } 
        }else{
                return $this->returnmsg(402,"旧密码错误");
         }
    }

    //个人动态发表
    public function create_dynamic($user_id,$latitude,$longitude,$user_address,$content){
        $time = date('Y-m-d H:i:s');
        if (!empty($user_address)) {
                $data = ['user_id'=>$user_id,'content'=>$content,'latitude'=>$latitude,'longitude'=>$longitude,'user_address'=>$user_address,'send_time'=>$time];
                $dynamic_id = Db::table('ym_user_dynamic')->insertGetId($data);
                Db::query("insert into ym_user_dynamic_upvoteCount values(null,'$dynamic_id',0)");
            }else{
                $data = ['user_id'=>$user_id,'content'=>$content,'latitude'=>null,'longitude'=>null,'user_address'=>null,'send_time'=>$time];
                $dynamic_id = Db::table('ym_user_dynamic')->insertGetId($data); 
                Db::query("insert into ym_user_dynamic_upvoteCount values(null,'$dynamic_id',0)");  
            }
        $files = Request::instance()->file('img');
        foreach($files as $file){
            $info = $file->move(ROOT_PATH . 'public' . DS. 'uploads'.DS.'user_dynamic_img');
            if ($info) {
                $path = '/uploads/user_dynamic_img/' . $info->getSaveName();
                $path = str_replace('\\', '/', $path);

                Db::query("insert into ym_user_dynamic_img values(null,'$dynamic_id','$path')");
            }
        }
        return $this->returnmsg(200,"发表动态成功");
    }

    //个人动态点赞
    public function dynamic_upvote($dynamic_id,$user_id){

        $time = date('Y-m-d H:i:s');
        $dynamic = Db::query("select user_id from ym_user_dynamic where dynamic_id = '$dynamic_id'");
        $be_user_id = $dynamic[0]['user_id'];
        $img = Db::query("select img_url from ym_user_dynamic_img where dynamic_id = '$dynamic_id' limit 1");
        $img_url = $img[0]['img_url'];

        $result = Db::query("select upvote from ym_user_dynamic_upvote where dynamic_id = '$dynamic_id'");
        $array = Db::query(" select count(*)from ym_user_dynamic_upvote where dynamic_id = '$dynamic_id'");
        $count = $array[0]['count(*)'];
        if (empty($result)) {

            Db::query("insert into ym_user_dynamic_upvote values(null,'$dynamic_id','$user_id',1)");
            Db::query("update ym_user_dynamic_upvoteCount set upvoteCount = 1 where dynamic_id = '$dynamic_id'");

            //推送消息
            $message_data = ['be_user_id'=>$be_user_id,'user_id'=>$user_id,'message_type'=>2,'create_time'=>$time];
            $m_id = Db::table('ym_message')->insertGetId($message_data);
            $upvote_data = ['m_id'=>$m_id,'module_type'=>1,'id'=>$dynamic_id,'img_url'=>$img_url];
            $m_upvote_id = Db::table('ym_message_upvote')->insertGetId($upvote_data);

            $user_name = Db::query("select user_name from user_info where user_id = '$user_id'");
            $name = $user_name[0]['user_name'];
            // $message = '关注了你';
            $be_user_id = strval($be_user_id);
            $this->push($be_user_id,$name.'赞了你的动态');
            return $this->returnmsg(200,"点赞成功");
        }else{
            Db::query("insert into ym_user_dynamic_upvote values(null,'$dynamic_id','$user_id',1)");
            Db::query("update ym_user_dynamic_upvoteCount set upvoteCount = '$count' + 1 where dynamic_id = '$dynamic_id'");

            //推送消息
            $message_data = ['be_user_id'=>$be_user_id,'user_id'=>$user_id,'message_type'=>2,'create_time'=>$time];
            $m_id = Db::table('ym_message')->insertGetId($message_data);
            $upvote_data = ['m_id'=>$m_id,'module_type'=>1,'id'=>$dynamic_id,'img_url'=>$img_url];
            $m_upvote_id = Db::table('ym_message_upvote')->insertGetId($upvote_data);

            $user_name = Db::query("select user_name from user_info where user_id = '$user_id'");
            $name = $user_name[0]['user_name'];
            // $message = '关注了你';
            $be_user_id = strval($be_user_id);
            $this->push($be_user_id,$name.'赞了你的动态');
            return $this->returnmsg(200,"点赞成功");
        }
    }

    //个人动态，评论(一级)
    public function dynamic_cmmt($dynamic_id,$user_id,$super_user_id,$super_cmmt_id,$cmmt_content){
        $time = date('Y-m-d H:i:s');
        $post = Db::query("select user_id from ym_user_dynamic where dynamic_id = '$dynamic_id'");
        $be_user_id = $post[0]['user_id'];
        $img = Db::query("select img_url from ym_user_dynamic_img where dynamic_id = '$dynamic_id' limit 1");
        $img_url = $img[0]['img_url'];
 
        if (!empty($super_user_id) && !empty($super_cmmt_id)) {
            
            $data = ['dynamic_id'=>$dynamic_id,'user_id'=>$user_id,'super_user_id'=>$super_user_id,'super_cmmt_id'=>$super_cmmt_id,'cmmt_content'=>$cmmt_content,'create_time'=>$time];
            $cmmt_id = Db::table('ym_user_dynamic_cmmt')->insertGetId($data);

            Db::query("insert into ym_user_dynamic_cmmt_upvoteCount values(null,'$cmmt_id','$dynamic_id',0)");

            $message_data = ['be_user_id'=>$super_user_id,'user_id'=>$user_id,'message_type'=>4,'create_time'=>$time];
            $m_id = Db::table('ym_message')->insertGetId($message_data);
            $reply_data = ['m_id'=>$m_id,'module_type'=>1,'id'=>$dynamic_id,'cmmt_id'=>$cmmt_id,'cmmt_content'=>$cmmt_content,'img_url'=>$img_url];
            $m_reply_id = Db::table('ym_message_reply')->insertGetId($reply_data);

            $user_name = Db::query("select user_name from user_info where user_id = '$user_id'");
            $name = $user_name[0]['user_name'];

            $this->push($super_user_id,$name.'回复了你的动态,'.$cmmt_content);
            return $this->returnmsg(200,'回复成功');
        }else{
            $data = ['dynamic_id'=>$dynamic_id,'user_id'=>$user_id,'super_user_id'=>null,'super_cmmt_id'=>null,'cmmt_content'=>$cmmt_content,'create_time'=>$time];
            $cmmt_id = Db::table('ym_user_dynamic_cmmt')->insertGetId($data);

            Db::query("insert into ym_user_dynamic_cmmt_upvoteCount values(null,'$cmmt_id','$dynamic_id',0)");

            //推送消息
            $message_data = ['be_user_id'=>$be_user_id,'user_id'=>$user_id,'message_type'=>3,'create_time'=>$time];
            $m_id = Db::table('ym_message')->insertGetId($message_data);
            $cmmt_data = ['m_id'=>$m_id,'module_type'=>1,'id'=>$dynamic_id,'cmmt_id'=>$cmmt_id,'content'=>$cmmt_content,'img_url'=>$img_url];
            $m_cmmt_id = Db::table('ym_message_cmmt')->insertGetId($cmmt_data);

            // Db::query("insert into ym_message_cmmt_dynamic values(null,'$m_cmmt_id','$dynamic_id','$cmmt_id','$cmmt_content','$img_url')");
            $user_name = Db::query("select user_name from user_info where user_id = '$user_id'");
            $name = $user_name[0]['user_name'];
            // $message = '关注了你';
            $be_user_id = strval($be_user_id);
            $this->push($be_user_id,$name.'评论了你的动态,'.$cmmt_content);
            return $this->returnmsg(200,'发表评论成功');
        }
    }

    public function show_dynamic_cmmt($user_id,$dynamic_id,$pageno){
        $pagesize = 10;
        $startno = $pageno *$pagesize;
        $result = Db::query("select a.cmmt_id,a.cmmt_content,a.create_time,b.user_id,b.user_name,b.small_user_icon as user_icon,c.cmmt_upvoteCount from ym_user_dynamic_cmmt as a join user_info as b on a.user_id = b.user_id join ym_user_dynamic_cmmt_upvoteCount as c on a.cmmt_id = c.cmmt_id where a.dynamic_id = '$dynamic_id' ORDER BY c.cmmt_upvoteCount desc,a.create_time desc limit {$startno} , {$pagesize}");
        $length = count($result);
        for ($i=0; $i <$length ; $i++) { 
            $cmmt_id = $result[$i]['cmmt_id'];
            $count = Db::query("select count(*) as count from ym_user_dynamic_cmmt where dynamic_id = '$dynamic_id'");
            $result[$i]['cmmt_count'] = $count[0]['count'];
            $super = Db::query("select super_user_id from ym_user_dynamic_cmmt where cmmt_id = '$cmmt_id'");
            $super_user_id = $super[0]['super_user_id'];
            if (!is_null($super_user_id)) {
                $user = Db::query("select user_id as super_user_id,user_name from user_info where user_id = '$super_user_id'");
                $result[$i]['super_user_id'] = $user[0]['super_user_id'];
                $result[$i]['super_user_name'] = $user[0]['user_name'];
            }else{
                $result[$i]['super_user_id'] = null;
                $result[$i]['super_user_name'] = null;
            }
            $upvote = Db::query("select cmmt_upvote from ym_user_dynamic_cmmt_upvote where cmmt_id = '$cmmt_id' and user_id = '$user_id'");
            // echo $upvote[0]['cmm_upvote'];
                if (is_null($upvote[0]['cmmt_upvote'])) {
                    $result[$i]['cmmt_upvote'] = 0;
                }else{
                    $result[$i]['cmmt_upvote'] = $upvote[0]['cmmt_upvote'];
                }
        }
        return $this->returnmsg(200,'个人动态评论',$result);
    }

    //个人动态，评论点赞
    public function dynamic_cmmt_upvote($dynamic_id,$cmmt_id,$user_id){

        $time = date('Y-m-d H:i:s');
        $dynamic = Db::query("select user_id from ym_user_dynamic where dynamic_id = '$dynamic_id'");
        $be_user_id = $dynamic[0]['user_id'];
        
        $img = Db::query("select img_url from ym_user_dynamic_img where dynamic_id = '$dynamic_id' limit 1");
        $img_url = $img[0]['img_url'];


        $result = Db::query("select cmmt_upvote from ym_user_dynamic_cmmt_upvote where dynamic_id = '$dynamic_id' and cmmt_id = '$cmmt_id'");
        $array = Db::query(" select cmmt_upvoteCount from ym_user_dynamic_cmmt_upvoteCount where dynamic_id = '$dynamic_id' and cmmt_id = '$cmmt_id'");
        $count = $array[0]['cmmt_upvoteCount'];
        if (empty($result)) {
            Db::query("insert into ym_user_dynamic_cmmt_upvote values(null,'$cmmt_id','$dynamic_id','$user_id',1)");
            Db::query("update ym_user_dynamic_cmmt_upvoteCount set cmmt_upvoteCount = 1 where dynamic_id = '$dynamic_id' and cmmt_id = '$cmmt_id'");

            //推送消息
            $message_data = ['be_user_id'=>$be_user_id,'user_id'=>$user_id,'message_type'=>2,'create_time'=>$time];
            $m_id = Db::table('ym_message')->insertGetId($message_data);
            $upvote_data = ['m_id'=>$m_id,'module_type'=>1,'id'=>$dynamic_id,'cmmt_id'=>$cmmt_id,'img_url'=>$img_url];
            $m_upvote_id = Db::table('ym_message_upvote')->insertGetId($upvote_data);

            // Db::query("insert into ym_message_upvote_dynamic values(null,'$m_upvote_id','$dynamic_id','$cmmt_id','$img_url')");
            $user_name = Db::query("select user_name from user_info where user_id = '$user_id'");
            $name = $user_name[0]['user_name'];
            // $message = '关注了你';
            $be_user_id = strval($be_user_id);
            $this->push($be_user_id,$name.'赞了你的动态,');
            return $this->returnmsg(200,"点赞成功");
        }else{
            Db::query("insert into ym_user_dynamic_cmmt_upvote values(null,'$cmmt_id','$dynamic_id','$user_id',1)");
            Db::query("update ym_user_dynamic_cmmt_upvoteCount set cmmt_upvoteCount = '$count' + 1 where dynamic_id = '$dynamic_id' and cmmt_id = '$cmmt_id'");

            //推送消息
            $message_data = ['be_user_id'=>$be_user_id,'user_id'=>$user_id,'message_type'=>2,'create_time'=>$time];
            $m_id = Db::table('ym_message')->insertGetId($message_data);
            $upvote_data = ['m_id'=>$m_id,'module_type'=>1,'id'=>$dynamic_id,'cmmt_id'=>$cmmt_id,'img_url'=>$img_url];
            $m_upvote_id = Db::table('ym_message_upvote')->insertGetId($upvote_data);

            // Db::query("insert into ym_message_upvote_dynamic values(null,'$m_upvote_id','$dynamic_id','$cmmt_id','$img_url')");
            $user_name = Db::query("select user_name from user_info where user_id = '$user_id'");
            $name = $user_name[0]['user_name'];
            // $message = '关注了你';
            $be_user_id = strval($be_user_id);
            $this->push($be_user_id,$name.'赞了你的动态');
            return $this->returnmsg(200,"点赞成功");
        }
    }

    //个人动态,删除文章12-23
    public function delete_user_dynamic($dynamic_id){
        Db::query("delete from ym_user_dynamic where dynamic_id = '$dynamic_id'");
        $result = Db::query("select *from ym_user_dynamic where dynamic_id = '$dynamic_id'");
        if (empty($result)) {
            Db::query("delete from ym_user_dynamic_img where dynamic_id = '$dynamic_id'");
            Db::query("delete from ym_user_dynamic_upvote where dynamic_id = '$dynamic_id'");
            Db::query("delete from ym_user_dynamic_upvoteCount where dynamic_id = '$dynamic_id'");
            Db::query("delete from ym_user_dynamic_cmmt where dynamic_id = '$dynamic_id'");
            Db::query("delete from ym_user_dynamic_cmmt_upvote where dynamic_id = '$dynamic_id'");
            Db::query("delete from ym_user_dynamic_cmmt_upvoteCount where dynamic_id = '$dynamic_id'");
            return $this->returnmsg(200,"删除成功");
        }else{
            return $this->returnmsg(400,"删除失败");
        }
    }

    //个人动态,删除文章评论12-22
    public function delete_dynamic_cmmt($dynamic_id,$cmmt_id){
        Db::query("delete from ym_user_dynamic_cmmt where dynamic_id = '$dynamic_id' and cmmt_id = '$cmmt_id'");
        $result = Db::query("select *from ym_user_dynamic_cmmt where dynamic_id = '$dynamic_id' and cmmt_id = '$cmmt_id'");
        if (empty($result)) {
            Db::query("delete from ym_user_dynamic_cmmt_upvote where dynamic_id = '$dynamic_id' and cmmt_id = '$cmmt_id'");
            Db::query("delete from ym_user_dynamic_cmmt_upvoteCount where dynamic_id = '$dynamic_id' and cmmt_id = '$cmmt_id'");
            return $this->returnmsg(200,"删除成功");
        }else{
            return $this->returnmsg(400,"删除失败");
        }
    }

    //显示主页
    public function show_homepage($user_id,$other_user_id){
        $str = '';
        if ($user_id != $other_user_id) {
            $result = Db::query("select b.user_id,b.user_name,b.user_icon,b.user_desc,b.background_img,c.pet_food,b.follow_count,b.fans_count from user_info as b join ym_pet_food as c on b.user_id = c.user_id where b.user_id = '$other_user_id' ");

            //判断是否已关注
            $follow_or_not = Db::query("select *from ym_user_follow where user_id = '$user_id' and follow_id = '$other_user_id'");

            $dynamic_ids = Db::query("select dynamic_id from ym_user_dynamic where user_id = '$other_user_id'");
            if (empty($dynamic_ids)) {
                $result[0]['upvoteCount'] = 0;
            }else{
                $length = count($dynamic_ids);
                for ($i=0; $i < $length; $i++) { 
                    $dynamic_id = $dynamic_ids[$i]['dynamic_id'];
                    $str.=','.$dynamic_id;
                }
                $ids = substr($str,1);

                $upvoteCount = Db::query("select sum(upvoteCount) as count from ym_user_dynamic_upvoteCount where dynamic_id in($ids)");

                $result[0]['upvoteCount'] = $upvoteCount[0]['count'];
            }
            if (empty($follow_or_not)) {
                $result[0]['follow_status'] = 0;
            }else{
                $result[0]['follow_status'] = 1;
            }
            return $this->returnmsg(200,'别人首页头部',$result);

        }else{//自己首页

            $result = Db::query("select b.user_id,b.user_name,b.user_icon,b.user_desc,b.background_img,c.pet_food,b.follow_count,b.fans_count from user_info as b join ym_pet_food as c on b.user_id = c.user_id where b.user_id = '$user_id' ");

            $dynamic_ids = Db::query("select dynamic_id from ym_user_dynamic where user_id = '$other_user_id'");
            if (empty($dynamic_ids)) {
                $result[0]['upvoteCount'] = 0;
            }else{
                $length = count($dynamic_ids);
                for ($i=0; $i < $length; $i++) { 
                    $dynamic_id = $dynamic_ids[$i]['dynamic_id'];
                    $str.=','.$dynamic_id;
                }
                $ids = substr($str,1);
                $upvoteCount = Db::query("select sum(upvoteCount) as count from ym_user_dynamic_upvoteCount where dynamic_id in($ids)");

                $result[0]['upvoteCount'] = $upvoteCount[0]['count'];
            }
            return $this->returnmsg(200,'个人首页头部',$result);
        }
    }

    //显示关注人动态
    public function follow_user_dynamic($user_id,$pageno){
        $pagesize = 3;
        $startno = $pageno *$pagesize;
        $ids = Db::query("select follow_id from ym_user_follow where user_id = '$user_id'");
        // var_dump($ids);
        if (!empty($ids)) {
            
            $length = count($ids);
            for ($i=0; $i < $length; $i++) { 
                $follow_id = $ids[$i]['follow_id'];
                $str.=','.$follow_id;
            }
            $follow_ids = substr($str,1);
            $dynamic = Db::query("select b.user_id,b.user_name,b.user_icon,a.dynamic_id,a.content,a.latitude as post_latitude,a.longitude as post_longitude,a.user_address,a.send_time from ym_user_dynamic as a left join user_info as b on a.user_id=b.user_id  where a.user_id in($follow_ids) ORDER BY a.send_time DESC limit {$startno},{$pagesize}");
            //join ym_user_dynamic_upvoteCount as c on a.dynamic_id = c.dynamic_id
            $length = count($dynamic);
            for ($i=0; $i < $length; $i++) { 
                $dynamic_id = $dynamic[$i]['dynamic_id'];
                $img = Db::query("select img_url from ym_user_dynamic_img where dynamic_id = '$dynamic_id'");
                $dynamic[$i]['img_urls'] = $img;
                $upvoteCount = Db::query("select upvoteCount from ym_user_dynamic_upvoteCount where dynamic_id = '$dynamic_id'");
                // var_dump($upvoteCount);
                $dynamic[$i]['upvoteCount'] = $upvoteCount[0]['upvoteCount'];
                $count = Db::query("select count(*) as count from ym_user_dynamic_cmmt where dynamic_id = '$dynamic_id'");
                $dynamic[$i]['cmmt_count'] = $count[0]['count'];
                $upvote = Db::query("select upvote from ym_user_dynamic_upvote where dynamic_id = '$dynamic_id' and user_id = '$user_id'");
                if (is_null($upvote[0]['upvote'])) {
                    $dynamic[$i]['upvote'] = 0;
                }else{
                    $dynamic[$i]['upvote'] = $upvote[0]['upvote'];
                }  
            }
            return $this->returnmsg(200,'关注人动态',$dynamic);
        }else{//没有关注的人
            return $this->returnmsg(200,'你还没有关注的人哦');
        }
    }

    //个人动态,显示图片12-22
    public function show_dynamic_img($user_id,$pageno){
        
        $pagesize = 3;
        $startno = $pageno *$pagesize;
        
        $result = Db::query("select dynamic_id,user_id from ym_user_dynamic where user_id = '$user_id' ORDER BY send_time desc limit {$startno},{$pagesize}");
        $count = count($result);
        for ($i=0; $i < $count; $i++) { 
            $dynamic_id = $result[$i]['dynamic_id'];
            $img_url = Db::query("select img_url from ym_user_dynamic_img where dynamic_id = '$dynamic_id' limit 1");
            $result[$i]['img_url'] = $img_url[0]['img_url'];
        }
        
        return $this->returnmsg(200,"动态图片",$result);
    }


    public function show_user_petinfo($user_id,$pageno){
        $pagesize = 3;
        $startno = $pageno * $pagesize;
        $result = Db::query("select a.pet_id,a.user_id,a.pet_name,a.pet_gender,a.pet_brith,a.pet_kind,a.pet_status,a.pet_icon,b.fans_count,c.pet_hungry_level from ym_pet as a join user_info as b on a.user_id = b.user_id join ym_pet_hungry as c on a.pet_id = c.pet_id where a.user_id = '$user_id' and a.permisstion_to_access = 1 ORDER BY a.pet_id desc limit {$startno},{$pagesize}");
        // var_dump($result);
        return $this->returnmsg(200,'message',$result);
    }

    public function update_pet_status($pet_id,$pet_status){
        Db::query("update ym_pet set pet_status = '$pet_status' where pet_id = '$pet_id'");
        return $this->returnmsg(200,'message');
    }

    public function show_user_dynamic($dynamic_id,$user_id){
        
        $dynamic = Db::query("select b.user_id,b.user_name,b.user_icon,a.dynamic_id,a.content,a.latitude as post_latitude,a.longitude as post_longitude,a.user_address,a.send_time,c.upvoteCount from ym_user_dynamic as a left join user_info as b on a.user_id=b.user_id join ym_user_dynamic_upvoteCount as c on a.dynamic_id = c.dynamic_id where a.dynamic_id = '$dynamic_id' ");
        
        $length = count($dynamic);
        for ($i=0; $i < $length; $i++) { 
            $dynamic_id = $dynamic[$i]['dynamic_id'];
            $img = Db::query("select img_url from ym_user_dynamic_img where dynamic_id = '$dynamic_id'");
            $dynamic[$i]['img_urls'] = $img;
            $count = Db::query("select count(*) as count from ym_user_dynamic_cmmt where dynamic_id = '$dynamic_id'");
            $dynamic[$i]['cmmt_count'] = $count[0]['count'];
            $upvote = Db::query("select upvote from ym_user_dynamic_upvote where dynamic_id = '$dynamic_id' and user_id = '$user_id'");
            if (is_null($upvote[0]['upvote'])) {
                $dynamic[$i]['upvote'] = 0;
            }else{
                $dynamic[$i]['upvote'] = $upvote[0]['upvote'];
            }  
        }
        return $this->returnmsg(200,"dynamic",$dynamic);
    }

    public function pet_manage($user_id){
        
        $result = Db::query("select pet_id,pet_name,pet_gender,pet_brith,pet_kind,pet_icon,permisstion_to_access from ym_pet where user_id = '$user_id'");
        // var_dump($result);
        return $this->returnmsg(200,'宠物信息',$result);
    }

    //添加宠物
    public function add_pet($user_id,$old_pet_id,$pet_name,$pet_gender,$pet_brith,$pet_kind){
        switch ($pet_gender) {
            case '男':
                $pet_gender = 0;
                break;
            case '女':
                $pet_gender = 1;
                break;
        }

        if (!empty($old_pet_id)) {
            $files = Request::instance()->file('img_url');
            $file = Request::instance()->file('pet_icon');
            if ($files && !$file) {
                $info = $files->move(ROOT_PATH . 'public' . DS. 'uploads'.DS.'pet_img');
                if ($info) {
                    $path = '/uploads/pet_img/' . $info->getSaveName();
                    $path = str_replace('\\', '/', $path);
                    Db::query("update ym_pet set permisstion_to_access = 0, pet_name = '$pet_name',pet_gender = '$pet_gender',pet_brith = '$pet_brith',pet_kind = '$pet_kind',img_url = '$path' where pet_id = '$old_pet_id'");
                    return $this->returnmsg(200,'修改宠物资料成功');
                }
            }elseif ($file && !$files) {
                $info_icon = $file->move(ROOT_PATH . 'public' . DS. 'uploads'.DS.'pet_icon');
                if ($info_icon) {
                    $icon_path = '/uploads/pet_icon/' . $info_icon->getSaveName();

                    $photo = $info_icon->getFilename();
                    $small_path = ROOT_PATH . 'public' . DS. 'uploads'.DS.'small_pet_icon'.DS.$photo;
                    $icon_path = str_replace('\\', '/', $icon_path);
                    $small_path = str_replace('\\', '/', $small_path);

                    // $image
                    $image = Image::open(request()->file('pet_icon'));
                    // 按照原图的比例生成一个最大为72*72的缩略图并保存为thumb.png
                    $image->thumb(72, 72, Image::THUMB_CENTER)->save($small_path);

                    $len = strlen(ROOT_PATH. 'public');

                    $small_path = substr_replace($small_path,'',0,$len);

                    Db::query("update ym_pet set permisstion_to_access = 0, pet_name = '$pet_name',pet_gender = '$pet_gender',pet_brith = '$pet_brith',pet_kind = '$pet_kind',pet_icon = '$icon_path',small_pet_icon = '$small_path' where pet_id = '$old_pet_id'");
                    return $this->returnmsg(200,'修改宠物资料成功');
                }
            }elseif (!$files && !$file) {
                Db::query("update ym_pet set permisstion_to_access = 0, pet_name = '$pet_name',pet_gender = '$pet_gender',pet_brith = '$pet_brith',pet_kind = '$pet_kind' where pet_id = '$old_pet_id'");
                    return $this->returnmsg(200,'修改宠物资料成功');
            }else{
                // 移动到框架应用根目录/public/uploads/ 目录下
                $info = $files->move(ROOT_PATH . 'public' . DS. 'uploads'.DS.'pet_img');
                $info_icon = $file->move(ROOT_PATH . 'public' . DS. 'uploads'.DS.'pet_icon');
                //$res = db('user')->where('user_id', $data['user_id'])->setField('user_icon', $head_img_path);
                if($info && $info_icon){
                    // 成功上传后 获取上传信息
                    // 输出 jpg
                    $path = '/uploads/pet_img/' . $info->getSaveName();
                    $icon_path = '/uploads/pet_icon/' . $info_icon->getSaveName();

                    $photo = $info_icon->getFilename();
                    $small_path = ROOT_PATH . 'public' . DS. 'uploads'.DS.'small_pet_icon'.DS.$photo;

                    $path = str_replace('\\', '/', $path);
                    $icon_path = str_replace('\\', '/', $icon_path);
                    $small_path = str_replace('\\', '/', $small_path);

                    // $image
                    $image = Image::open(request()->file('pet_icon'));
                    // 按照原图的比例生成一个最大为72*72的缩略图并保存为thumb.png
                    $image->thumb(72, 72, Image::THUMB_CENTER)->save($small_path);

                    $len = strlen(ROOT_PATH. 'public');

                    $small_path = substr_replace($small_path,'',0,$len);

                    Db::query("update ym_pet set permisstion_to_access = 0, pet_name = '$pet_name',pet_gender = '$pet_gender',pet_brith = '$pet_brith',pet_kind = '$pet_kind',pet_icon = '$icon_path',small_pet_icon = '$small_path',img_url = '$path' where pet_id = '$old_pet_id'");
                    return $this->returnmsg(200,'修改宠物资料成功,请等待审核');

                    // $data = ['user_id'=>$user_id,'pet_name'=>$pet_name,'pet_gender'=>$pet_gender,'pet_brith'=>$pet_brith,'pet_kind'=>$pet_kind,'pet_icon'=>$icon_path,'small_pet_icon'=>$small_path,'img_url'=>$path];
                    // $pet_id = Db::table('ym_pet')->insertGetId($data);
                    // Db::query("insert into ym_pet values(null,'$user_id','$pet_name','$pet_gender','$pet_brith','$pet_kind',default,default,'$icon_path','$small_path','$path')");
                    // echo $pet_id;
                    // Db::query("insert into ym_pet_hungry values(null,'$pet_id',default,default,default,default)");
                    // $this->delete_pet($old_pet_id);
                }
            }
        }else{

            $files = Request::instance()->file('img_url');
            $file = Request::instance()->file('pet_icon');
            // 移动到框架应用根目录/public/uploads/ 目录下
            // $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
            $info = $files->move(ROOT_PATH . 'public' . DS. 'uploads'.DS.'pet_img');
            $info_icon = $file->move(ROOT_PATH . 'public' . DS. 'uploads'.DS.'pet_icon');
            //$res = db('user')->where('user_id', $data['user_id'])->setField('user_icon', $head_img_path);
            if($info && $info_icon){
                // 成功上传后 获取上传信息
                // 输出 jpg
                $path = '/uploads/pet_img/' . $info->getSaveName();
                $icon_path = '/uploads/pet_icon/' . $info_icon->getSaveName();

                $photo = $info_icon->getFilename();
                $small_path = ROOT_PATH . 'public' . DS. 'uploads'.DS.'small_pet_icon'.DS.$photo;

                $path = str_replace('\\', '/', $path);
                $icon_path = str_replace('\\', '/', $icon_path);
                $small_path = str_replace('\\', '/', $small_path);

                // $image
                $image = Image::open(request()->file('pet_icon'));
                // 按照原图的比例生成一个最大为72*72的缩略图并保存为thumb.png
                $image->thumb(72, 72, Image::THUMB_CENTER)->save($small_path);

                $len = strlen(ROOT_PATH. 'public');

                $small_path = substr_replace($small_path,'',0,$len);
                $data = ['user_id'=>$user_id,'pet_name'=>$pet_name,'pet_gender'=>$pet_gender,'pet_brith'=>$pet_brith,'pet_kind'=>$pet_kind,'pet_icon'=>$icon_path,'small_pet_icon'=>$small_path,'img_url'=>$path];
                $pet_id = Db::table('ym_pet')->insertGetId($data);
                // Db::query("insert into ym_pet values(null,'$user_id','$pet_name','$pet_gender','$pet_brith','$pet_kind',default,default,'$icon_path','$small_path','$path')");
                // echo $pet_id;
                Db::query("insert into ym_pet_hungry values(null,'$pet_id',default,default,default,default)");
                return $this->returnmsg(200,"添加宠物信息成功,请等待审核");
            }
        }
    }

    public function delete_pet($pet_id){
        Db::query("delete from ym_pet where pet_id = '$pet_id'");//删除这只宠物
        Db::query("delete from ym_pet_hungry where pet_id = '$pet_id'");//删除这支宠物的饥饿值
        return $this->returnmsg(200,'删除宠物成功');
    }

    public function edit_pet_info($pet_id){
        $result = Db::query("select pet_name,pet_brith,pet_kind,pet_gender,pet_icon,img_url from ym_pet where pet_id = '$pet_id'");//点击修改资料，将此宠物信息显示
        return $this->returnmsg(200,'pet_info',$result);
    }

    //修改宠物资料
    public function modify_pet_info($pet_id,$pet_name,$pet_brith,$pet_kind,$pet_gender){
        switch ($pet_gender) {
            case '男':
                $pet_gender = 0;
                break;
            case '女':
                $pet_gender = 1;
                break;
        }
        $file = Request::file('pet_icon');
        if ($file) {//如果修改了头像
            
            $info_icon = $file->move(ROOT_PATH . 'public' . DS. 'uploads'.DS.'pet_icon');
            //$res = db('user')->where('user_id', $data['user_id'])->setField('user_icon', $head_img_path);
            if($info_icon){
                // 成功上传后 获取上传信息
                // 输出 jpg
                $icon_path = '/uploads/pet_icon/' . $info_icon->getSaveName();

                $photo = $info_icon->getFilename();
                $small_path = ROOT_PATH . 'public' . DS. 'uploads'.DS.'small_pet_icon'.DS.$photo;

                $icon_path = str_replace('\\', '/', $icon_path);
                $small_path = str_replace('\\', '/', $small_path);

                // $image
                $image = Image::open(request()->file('pet_icon'));
                // 按照原图的比例生成一个最大为72*72的缩略图并保存为thumb.png
                $image->thumb(72, 72, Image::THUMB_CENTER)->save($small_path);

                $len = strlen(ROOT_PATH. 'public');//获取需要截取的路径

                $small_path = substr_replace($small_path,'',0,$len);//将上面的路径截取

                Db::query("update ym_pet set pet_name = '$pet_name',pet_brith = '$pet_brith',pet_kind = '$pet_kind',pet_icon = '$icon_path',small_pet_icon = '$small_path' where pet_id = '$pet_id'");
                return $this->returnmsg(200,'修改宠物信息成功');
            }
        }else{//没有修改头像，直接将参数修改进数据库
            Db::query("update ym_pet set pet_name = '$pet_name',pet_brith = '$pet_brith',pet_kind = '$pet_kind' where pet_id = '$pet_id'");
            return $this->returnmsg(200,'修改宠物信息成功');
        }
    }

    //返回随手拍图片
    public function get_snapshot_img(){
        
        $id = Db::query("select distinct circle_id from ym_snapshot_posts ORDER BY circle_id ASC");
        $length = count($id);
        $arr = array();
        for ($i=0; $i < $length; $i++) { 
            $circle_id = $id[$i]['circle_id'];
            $result = Db::query("select a.circle_id,a.circle_title,a.circle_subtitle,a.circle_img,count(distinct b.user_id) as count from ym_snapshot_circle as a join ym_snapshot_posts as b on a.circle_id = b.circle_id where b.circle_id = '$circle_id'");
            array_push($arr,$result[0]);
        }
        return $this->returnmsg(200,"随手拍",$arr);
    }


    
    public function snapshot_posts($user_id,$circle_id,$latitude,$longitude,$address,$content){
        
        $time = date('Y-m-d H:i:s');
        if (!empty($address)) {
                $data = ['circle_id'=>$circle_id,'user_id'=>$user_id,'content'=>$content,'post_latitude'=>$latitude,'post_longitude'=>$longitude,'user_address'=>$address,'send_time'=>$time];
                $post_id = Db::table('ym_snapshot_posts')->insertGetId($data);

                Db::query("insert into ym_posts_upvotecount values(null,'$post_id',0)");
                
            }else{
                $data = ['circle_id'=>$circle_id,'user_id'=>$user_id,'content'=>$content,'post_latitude'=>null,'post_longitude'=>null,'user_address'=>null,'send_time'=>$time];
                $post_id = Db::table('ym_snapshot_posts')->insertGetId($data);
                
                Db::query("insert into ym_posts_upvotecount values(null,'$post_id',0)");
            }
        $files = Request::instance()->file('img');
        foreach($files as $file){
            $info = $file->move(ROOT_PATH . 'public' . DS. 'uploads'.DS.'snapshot_img');
            if ($info) {
                $path = '/uploads/snapshot_img/' . $info->getSaveName();
                $path = str_replace('\\', '/', $path);
                // echo $path."<br />";

                Db::query("insert into ym_snapshot_img values(null,'$post_id','$path')");
            
            }
        }
        return $this->returnmsg(200,"发表话题成功");
    }


    public function get_hot_post($user_id,$circle_id,$pageno,$type){

        $startno = $pageno * 3;
        if ($type == 'hot') {
            
            $posts = Db::query("select distinct b.user_id,b.user_name,b.user_icon,c.circle_title,c.circle_subtitle,c.circle_desc,c.circle_big_img,a.post_id,a.content,a.post_latitude,a.post_longitude,a.user_address,a.send_time,e.upvoteCount from ym_snapshot_posts as a left join user_info as b on a.user_id=b.user_id left join ym_snapshot_circle as c on a.circle_id=c.circle_id join ym_posts_upvoteCount as e on a.post_id = e.post_id  where  c.circle_id = '$circle_id' ORDER BY e.upvoteCount desc limit {$startno},3");
            $length = count($posts);
            for ($i=0; $i < $length; $i++) { 
                $post_id = $posts[$i]['post_id'];
                $img = Db::query("select img_url from ym_snapshot_img where post_id = '$post_id'");
                $posts[$i]['img_urls'] = $img;
                $count = Db::query("select count(*) as count from ym_snapshot_cmmt where post_id = '$post_id'");
                $posts[$i]['cmmt_count'] = $count[0]['count'];
                $upvote = Db::query("select upvote from ym_snapshot_posts_upvote where post_id = '$post_id' and user_id = '$user_id'");
                if (is_null($upvote[0]['upvote'])) {
                    $posts[$i]['upvote'] = 0;
                }else{

                    $posts[$i]['upvote'] = $upvote[0]['upvote'];
              }  
            }

            return $this->returnmsg(200,"posts",$posts);
        }elseif ($type == 'new') {
            $posts = Db::query("select distinct b.user_id,b.user_name,b.user_icon,c.circle_title,c.circle_subtitle,c.circle_desc,c.circle_big_img,a.post_id,a.content,a.post_latitude,a.post_longitude,a.user_address,a.send_time,e.upvoteCount from ym_snapshot_posts as a left join user_info as b on a.user_id=b.user_id left join ym_snapshot_circle as c on a.circle_id=c.circle_id join ym_posts_upvoteCount as e on a.post_id = e.post_id  where c.circle_id = '$circle_id' ORDER BY a.send_time desc limit {$startno},3");
            $length = count($posts);
            for ($i=0; $i < $length; $i++) { 
                $post_id = $posts[$i]['post_id'];
                $img = Db::query("select img_url from ym_snapshot_img where post_id = '$post_id'");
                $posts[$i]['img_urls'] = $img;
                $count = Db::query("select count(*) as count from ym_snapshot_cmmt where post_id = '$post_id'");
                $posts[$i]['cmmt_count'] = $count[0]['count'];

                $upvote = Db::query("select upvote from ym_snapshot_posts_upvote where post_id = '$post_id' and user_id = '$user_id'");
                if (is_null($upvote[0]['upvote'])) {
                    $posts[$i]['upvote'] = 0;
                }else{

                    $posts[$i]['upvote'] = $upvote[0]['upvote'];
              }  
            }

            return $this->returnmsg(200,"posts",$posts);
        }
    }

    //随手拍,删除文章11-10
    public function delete_snapshot_post($post_id){
        Db::query("delete from ym_snapshot_posts where post_id = '$post_id'");
        $result = Db::query("select *from  ym_snapshot_posts where post_id = '$post_id'");
        if (empty($result)) {
            Db::query("delete from ym_snapshot_img where post_id = '$post_id'");
            Db::query("delete from ym_snapshot_posts_upvote where post_id = '$post_id'");
            Db::query("delete from ym_posts_upvoteCount where post_id = '$post_id'");
            Db::query("delete from ym_snapshot_cmmt where post_id = '$post_id'");
            Db::query("delete from ym_snapshot_cmmt_upvote where post_id = '$post_id'");
            Db::query("delete from ym_cmmt_upvoteCount where post_id = '$post_id'");
            return $this->returnmsg(200,"删除成功");
        }else{
            return $this->returnmsg(400,"删除失败");
        }
    }

    //随手拍点赞
    public function posts_upvote($post_id,$user_id){

        $time = date('Y-m-d H:i:s');
        $post = Db::query("select user_id from ym_snapshot_posts where post_id = '$post_id'");
        $be_user_id = $post[0]['user_id'];
        $img = Db::query("select img_url from ym_snapshot_img where post_id = '$post_id' limit 1");
        $img_url = $img[0]['img_url'];

        $result = Db::query("select upvote from ym_snapshot_posts_upvote where post_id = '$post_id'");
        $array = Db::query(" select count(*)from ym_snapshot_posts_upvote where post_id = '$post_id'");
        $count = $array[0]['count(*)'];
        if (empty($result)) {
            Db::query("insert into ym_snapshot_posts_upvote values(null,'$post_id','$user_id',1)");
            Db::query("update ym_posts_upvoteCount set upvoteCount = 1 where post_id = '$post_id'");

            //推送消息
            $message_data = ['be_user_id'=>$be_user_id,'user_id'=>$user_id,'message_type'=>2,'create_time'=>$time];
            $m_id = Db::table('ym_message')->insertGetId($message_data);
            $upvote_data = ['m_id'=>$m_id,'module_type'=>0,'id'=>$post_id,'img_url'=>$img_url];
            $m_upvote_id = Db::table('ym_message_upvote')->insertGetId($upvote_data);

            // Db::query("insert into ym_message_upvote_post values(null,'$m_upvote_id','$post_id',default,'$img_url')");
            $user_name = Db::query("select user_name from user_info where user_id = '$user_id'");
            $name = $user_name[0]['user_name'];
            // $message = '关注了你';
            $be_user_id = strval($be_user_id);
            $this->push($be_user_id,$name.'赞了你的话题帖子');
            return $this->returnmsg(200,"点赞成功");
        }else{
            Db::query("insert into ym_snapshot_posts_upvote values(null,'$post_id','$user_id',1)");
            Db::query("update ym_posts_upvoteCount set upvoteCount = '$count' + 1 where post_id = '$post_id'");

            //推送消息
            $message_data = ['be_user_id'=>$be_user_id,'user_id'=>$user_id,'message_type'=>2,'create_time'=>$time];
            $m_id = Db::table('ym_message')->insertGetId($message_data);
            $upvote_data = ['m_id'=>$m_id,'module_type'=>0,'id'=>$post_id,'img_url'=>$img_url];
            $m_upvote_id = Db::table('ym_message_upvote')->insertGetId($upvote_data);

            // Db::query("insert into ym_message_upvote_post values(null,'$m_upvote_id','$post_id',default,'$img_url')");
            $user_name = Db::query("select user_name from user_info where user_id = '$user_id'");
            $name = $user_name[0]['user_name'];
            // $message = '关注了你';
            $be_user_id = strval($be_user_id);
            $this->push($be_user_id,$name.'赞了你的话题帖子');
            return $this->returnmsg(200,"点赞成功");
        }
    }

    //随手拍，评论(一级)
    public function posts_cmmt($post_id,$user_id,$super_user_id,$super_cmmt_id,$cmmt_content){
        $time = date('Y-m-d H:i:s');
        $post = Db::query("select user_id from ym_snapshot_posts where post_id = '$post_id'");
        $be_user_id = $post[0]['user_id'];
        $img = Db::query("select img_url from ym_snapshot_img where post_id = '$post_id' limit 1");
        $img_url = $img[0]['img_url'];
        // base64_decode($cmmt_content);
        if (!empty($super_user_id) && !empty($super_cmmt_id)) {
            
            $data = ['post_id'=>$post_id,'user_id'=>$user_id,'super_user_id'=>$super_user_id,'super_cmmt_id'=>$super_cmmt_id,'cmmt_content'=>$cmmt_content,'create_time'=>$time];
            $cmmt_id = Db::table('ym_snapshot_cmmt')->insertGetId($data);

            Db::query("insert into ym_cmmt_upvoteCount values(null,'$cmmt_id','$post_id',0)");


            $message_data = ['be_user_id'=>$super_user_id,'user_id'=>$user_id,'message_type'=>4,'create_time'=>$time];
            $m_id = Db::table('ym_message')->insertGetId($message_data);
            $reply_data = ['m_id'=>$m_id,'module_type'=>0,'id'=>$post_id,'cmmt_id'=>$cmmt_id,'cmmt_content'=>$cmmt_content,'img_url'=>$img_url];
            $m_reply_id = Db::table('ym_message_reply')->insertGetId($reply_data);

            $user_name = Db::query("select user_name from user_info where user_id = '$user_id'");
            $name = $user_name[0]['user_name'];
            // $message = '关注了你';
            $be_user_id = strval($be_user_id);
            $this->push($be_user_id,$name.'评论了你的话题帖子,'.$cmmt_content);
            return $this->returnmsg(200,'回复成功');
        }else{
            $data = ['post_id'=>$post_id,'user_id'=>$user_id,'cmmt_content'=>$cmmt_content,'create_time'=>$time];
            $cmmt_id = Db::table('ym_snapshot_cmmt')->insertGetId($data);

            Db::query("insert into ym_cmmt_upvoteCount values(null,'$cmmt_id','$post_id',0)");
            
            //推送消息
            $message_data = ['be_user_id'=>$be_user_id,'user_id'=>$user_id,'message_type'=>3,'create_time'=>$time];
            $m_id = Db::table('ym_message')->insertGetId($message_data);
            $cmmt_data = ['m_id'=>$m_id,'module_type'=>0,'id'=>$post_id,'content'=>$cmmt_content,'img_url'=>$img_url];
            $m_cmmt_id = Db::table('ym_message_cmmt')->insertGetId($cmmt_data);

            $user_name = Db::query("select user_name from user_info where user_id = '$user_id'");
            $name = $user_name[0]['user_name'];
            // $message = '关注了你';
            $be_user_id = strval($be_user_id);
            $this->push($be_user_id,$name.'评论了你的话题帖子,'.$cmmt_content);
            return $this->returnmsg(200,'发表评论成功',$cmmt_content);
        }
    }

    //显示随手拍单个话题帖子
    public function show_snapshot_post($post_id,$user_id){
        
        $post = Db::query("select b.user_id,b.user_name,b.user_icon,a.post_id,a.content,a.post_latitude,a.post_longitude,a.user_address,a.send_time,c.upvoteCount from ym_snapshot_posts as a left join user_info as b on a.user_id=b.user_id join ym_posts_upvoteCount as c on a.post_id = c.post_id where a.post_id = '$post_id' ");
        
        $length = count($post);
        for ($i=0; $i < $length; $i++) { 
            $post_id = $post[$i]['post_id'];
            $img = Db::query("select img_url from ym_snapshot_img where post_id = '$post_id'");
            $post[$i]['img_urls'] = $img;
            $count = Db::query("select count(*) as count from ym_snapshot_cmmt where post_id = '$post_id'");
            $post[$i]['cmmt_count'] = $count[0]['count'];
            $upvote = Db::query("select upvote from ym_snapshot_posts_upvote where post_id = '$post_id' and user_id = '$user_id'");
            if (is_null($upvote[0]['upvote'])) {
                $post[$i]['upvote'] = 0;
            }else{
                $post[$i]['upvote'] = $upvote[0]['upvote'];
            }  
        }
        return $this->returnmsg(200,"post",$post);
    }

    public function show_post_cmmt($user_id,$post_id,$pageno){
        $pagesize = 10;
        $startno = $pageno *$pagesize;
        $result = Db::query("select a.cmmt_id,a.cmmt_content,a.create_time,b.user_id,b.user_name,b.small_user_icon as user_icon,c.cmmt_upvoteCount from ym_snapshot_cmmt as a join user_info as b on a.user_id = b.user_id join ym_cmmt_upvoteCount as c on a.cmmt_id = c.cmmt_id where a.post_id = '$post_id' ORDER BY c.cmmt_upvoteCount desc,a.create_time desc limit {$startno} , {$pagesize}");
        $length = count($result);
        for ($i=0; $i <$length ; $i++) { 
            $cmmt_id = $result[$i]['cmmt_id'];
            $count = Db::query("select count(*) as count from ym_snapshot_cmmt where post_id = '$post_id'");
            $result[$i]['cmmt_count'] = $count[0]['count'];
            $super = Db::query("select super_user_id from ym_snapshot_cmmt where cmmt_id = '$cmmt_id'");
            $super_user_id = $super[0]['super_user_id'];
            if (!is_null($super_user_id)) {
                $user = Db::query("select user_id as super_user_id,user_name from user_info where user_id = '$super_user_id'");
                $result[$i]['super_user_id'] = $user[0]['super_user_id'];
                $result[$i]['super_user_name'] = $user[0]['user_name'];
            }else{
                $result[$i]['super_user_id'] = null;
                $result[$i]['super_user_name'] = null;
            }
            $upvote = Db::query("select cmmt_upvote from ym_snapshot_cmmt_upvote where cmmt_id = '$cmmt_id' and user_id = '$user_id'");
            // echo $upvote[0]['cmm_upvote'];
                if (is_null($upvote[0]['cmmt_upvote'])) {
                    $result[$i]['cmmt_upvote'] = 0;
                }else{
                    $result[$i]['cmmt_upvote'] = $upvote[0]['cmmt_upvote'];
                }
        }
        return $this->returnmsg(200,'随手拍评论',$result);
    }

    //随手拍,删除文章评论11-10
    public function delete_snapshot_post_cmmt($post_id,$cmmt_id){
        Db::query("delete from ym_snapshot_cmmt where post_id = '$post_id' and cmmt_id = '$cmmt_id'");
        $result = Db::query("select *from ym_snapshot_cmmt where post_id = '$post_id' and cmmt_id = '$cmmt_id'");
        if (empty($result)) {
            Db::query("delete from ym_snapshot_cmmt_upvote where post_id = '$post_id' and cmmt_id = '$cmmt_id'");
            Db::query("delete from ym_cmmt_upvoteCount where post_id = '$post_id' and cmmt_id = '$cmmt_id'");
            return $this->returnmsg(200,"删除成功");
        }else{
            return $this->returnmsg(400,"删除失败");
        }
    }

    //评论点赞
    public function cmmt_upvote($post_id,$cmmt_id,$user_id){

        $time = date('Y-m-d H:i:s');
        $cmmt = Db::query("select user_id from ym_snapshot_cmmt where post_id = '$post_id' and cmmt_id = '$cmmt_id'");
        $be_user_id = $cmmt[0]['user_id'];
        $img = Db::query("select img_url from ym_snapshot_img where post_id = '$post_id' limit 1");
        $img_url = $img[0]['img_url'];

        $result = Db::query("select cmmt_upvote from ym_snapshot_cmmt_upvote where post_id = '$post_id' and cmmt_id = '$cmmt_id'");
        $array = Db::query(" select cmmt_upvoteCount from ym_cmmt_upvotecount where post_id = '$post_id' and cmmt_id = '$cmmt_id'");
        $count = $array[0]['cmmt_upvoteCount'];
        if (empty($result)) {
            Db::query("insert into ym_snapshot_cmmt_upvote values(null,'$cmmt_id','$post_id','$user_id',1)");
            Db::query("update ym_cmmt_upvotecount set cmmt_upvoteCount = 1 where post_id = '$post_id' and cmmt_id = '$cmmt_id'");

            //推送消息
            $message_data = ['be_user_id'=>$be_user_id,'user_id'=>$user_id,'message_type'=>2,'create_time'=>$time];
            $m_id = Db::table('ym_message')->insertGetId($message_data);
            $upvote_data = ['m_id'=>$m_id,'module_type'=>0,'id'=>$post_id,'cmmt_id'=>$cmmt_id,'img_url'=>$img_url];
            $m_upvote_id = Db::table('ym_message_upvote')->insertGetId($upvote_data);

            $user_name = Db::query("select user_name from user_info where user_id = '$user_id'");
            $name = $user_name[0]['user_name'];
            // $message = '关注了你';
            $be_user_id = strval($be_user_id);
            $this->push($be_user_id,$name.'赞了你的评论');
            return $this->returnmsg(200,"点赞成功");
        }else{
            Db::query("insert into ym_snapshot_cmmt_upvote values(null,'$cmmt_id','$post_id','$user_id',1)");
            Db::query("update ym_cmmt_upvotecount set cmmt_upvoteCount = '$count' + 1 where post_id = '$post_id' and cmmt_id = '$cmmt_id'");

            //推送消息
            $message_data = ['be_user_id'=>$be_user_id,'user_id'=>$user_id,'message_type'=>2,'create_time'=>$time];
            $m_id = Db::table('ym_message')->insertGetId($message_data);
            $upvote_data = ['m_id'=>$m_id,'module_type'=>0,'id'=>$post_id,'cmmt_id'=>$cmmt_id,'img_url'=>$img_url];
            $m_upvote_id = Db::table('ym_message_upvote')->insertGetId($upvote_data);

            $user_name = Db::query("select user_name from user_info where user_id = '$user_id'");
            $name = $user_name[0]['user_name'];

            $be_user_id = strval($be_user_id);
            $this->push($be_user_id,$name.'赞了你的评论');
            return $this->returnmsg(200,"点赞成功");
        }
    }

    //转发
    public function posts_forward($post_id,$user_id,$super_user_id){
        $res = Db::query("select user_name,user_icon from user_info where user_id = '$user_id'");
        $super_res = Db::query("select user_name,user_icon from user_info where user_id = '$super_user_id'");
        
        $posts = Db::query("select *from ym_snapshot_posts where post_id = '$post_id' and user_id = '$super_user_id'");
        foreach ($res as $rows) {}
        $user_name = $rows['user_name'];
        $user_icon = $rows['user_icon'];

        foreach ($super_res as $super_rows) {}
        $super_user_name = $super_rows['user_name'];
        $super_user_icon = $super_rows['user_icon'];

        

        foreach ($posts as $post) {}
        $content = $post['content'];
        $circle_id = $post['circle_id'];

        $circles = Db::query("select *from ym_snapshot_circle where circle_id = '$circle_id'");

        foreach ($circles as $new) {}
        $title = $new['circle_title'];
        $sub_title = $new['circle_subtitle'];
        $img = $new['circle_img'];

        $time = date("Y-m-d h:i:s");
        $forward_user = array('名称' =>$user_name,'头像' =>$user_icon);
        $user = array('名称' => $super_user_name,'头像' => $super_user_icon,'内容' => $content,'时间'=> $time);
        $arr = array('转发者' =>  $forward_user,  '被转发者' => $user);

        Db::query("insert into ym_snapshot_forward values(null,'$post_id','$user_id','$super_user_id',now())");

        Db::query("insert into ym_snapshot_posts values(null,'$circle_id','$user_id','$content',now())");
        
        Db::query("insert into ym_snapshot_circle values(null,'$title','$sub_title','$img')");

        return $this->returnmsg(200,"转发成功",$arr);
    }

    //宠物医院
    
    public function hospital($latitude,$longitude,$pageno){
        $pagesize = 20;
        $startno = $pageno*$pagesize;
        $result = Db::query("select pet_hospital_id,pet_hospital_name,latitude,longitude,pet_hospital_first_img from ym_pet_hospital limit {$startno},{$pagesize}");
        $count = Db::query("select count(*) as count from ym_pet_hospital");
        $length = count($result);
        for ($i=0; $i < $length; $i++) { 
            $distance = $this->calculate_distance($latitude,$longitude,$result[$i]['latitude'],$result[$i]['longitude']);
            $result[$i]['distance'] = $distance;
            $result[$i]['type'] = 1;
            $result[$i]['count'] = $count[0]['count'];
        }
        return $this->returnmsg(200,'pet_hospital',$result);
    }

    //宠物医院详情
    
    public function pet_hospital($pet_hospital_id){
        $result = Db::query("select pet_hospital_name,hospital_tel,pet_hospital_address,pet_hospital_business_hours from ym_pet_hospital where pet_hospital_id = '$pet_hospital_id'");

        $img = Db::query("select pet_hospital_img from ym_pet_hospital_img where pet_hospital_id = '$pet_hospital_id'");
        $imgs = [];
        $length = count($img);
        for ($i=0; $i < $length; $i++) { 
            $imgs[] = $img[$i]['pet_hospital_img'];
        }
        $result[0]['pet_hospital_imgs'] = $imgs;
        $result[0]['type'] = 1;
        return $this->returnmsg(200,'pet_hospital',$result);
    }

    // 猫咖
    public function show_cat_cafes($latitude,$longitude,$pageno){
        $pagesize = 5;
        $startno = $pageno *$pagesize;
        $result = Db::query("select cafe_id,cafe_name,latitude,longitude,cafe_first_img from ym_cat_cafe limit {$startno},{$pagesize}");
        $count = Db::query("select count(*) as count from ym_cat_cafe");
        $length = count($result);
        for ($i=0; $i < $length; $i++) { 
            $distance = $this->calculate_distance($latitude,$longitude,$result[$i]['latitude'],$result[$i]['longitude']);
            $result[$i]['distance'] = $distance;
            $result[$i]['type'] = 0;
            $result[$i]['count'] = $count[0]['count'];
        }
        return $this->returnmsg(200,'cat_cafes',$result);
    }

    //猫咖详情
    public function show_cat_cafe($cafe_id){

        $result = Db::query("select cafe_name,cafe_tel,cafe_address,cafe_business_hours from ym_cat_cafe where cafe_id = '$cafe_id'");

        $img = Db::query("select cafe_img from ym_cat_cafe_img where cafe_id = '$cafe_id'");
        $length = count($img);
        $imgs = [];
        for ($i=0; $i < $length; $i++) { 
            $imgs[] = $img[$i]['cafe_img'];
        }
        //猫咪
        $cat = Db::query("select *from ym_cafe_cats where cafe_id = '$cafe_id'");
        $cat_length = count($cat);
        $cats = [];
        for ($i=0; $i < $cat_length; $i++) { 
            $cats[] = $cat[$i];
        }
        $result[0]['cafe_imgs'] = $imgs;
        $result[0]['cat_info'] = $cats;
        $result[0]['type'] = 0;
        return $this->returnmsg(200,'cat_cafe',$result);
    }

    //显示猫的照片
    public function show_cat_img($cat_id){
        $result = Db::query("select *from ym_cafe_cats where cat_id = '$cat_id'");
        return $this->returnmsg(200,'cat_big_img',$result);
    }

    // 宠记发表动态(官方发表)
    public function petDiary_notes($user_id,$title,$note_content){
        $file = Request::instance()->file('note_img');

        $info = $file->move(ROOT_PATH . 'public' . DS. 'uploads'.DS.'note_img');
        if ($info) {
            $path = '/uploads/note_img/' . $info->getSaveName();
            $path = str_replace('\\', '/', $path);

            Db::query("insert into ym_petDiary_notes values(null,'$user_id','$title','$note_content',default,now())");
            $id = Db::query("select note_id from ym_petDiary_notes where user_id = '$user_id'");
            $note_id = $id[0]['note_id'];
            Db::query("insert into ym_petDiary_notes_img values(null,'$note_id','$path')");

            $notes = Db::table('ym_petDiary_notes')->alias('a')->join('ym_petDiary_notes_img b','a.note_id = b.note_id')->field(['a.user_id','a.title','a.note_content','a.create_time','b.note_img'])->where('a.user_id',$user_id)->where('b.note_id',$note_id)->select();
            
            }
        return $this->returnmsg(200,"发表动态成功",$notes);
    }

    //显示文章,更新阅读量11-10
    public function show_notes($note_id) {
        $reading = Db::query("select amount_of_reading from ym_petDiary_notes where note_id = '$note_id'");
        $amount_of_reading = $reading[0]['amount_of_reading'];
        $amount_of_reading ++;
        Db::query("update ym_petDiary_notes set amount_of_reading = '$amount_of_reading' where note_id = '$note_id'");
        $result = Db::query("select * from ym_petDiary_notes where note_id = '$note_id'");
        return $this->returnmsg(200,"显示文章",$result);
    }

    //删除文章11-10
    public function delete_petDiary_note($note_id){
        Db::query("delete from ym_petDiary_notes where note_id = '$note_id'");
        $result = Db::query("select *from ym_petDiary_notes where note_id = '$note_id'");
        if (empty($result)) {
            Db::query("delete from ym_petDiary_notes_img where note_id = '$note_id'");
            Db::query("delete from ym_petDiary_notes_upvote where note_id = '$note_id'");
            Db::query("delete from ym_notes_upvotecount where note_id = '$note_id'");
            return $this->returnmsg(200,"删除成功");
        }else{
            return $this->returnmsg(400,"删除失败");
        }
    }


    //文章点赞和取消点赞
    public function notes_upvote($note_id,$user_id){

        $result = Db::query("select note_upvote from ym_petDiary_notes_upvote where user_id = '$user_id' and note_id = '$note_id'");
        $array = Db::query(" select count(*)from ym_petDiary_notes_upvote where note_id = '$note_id'");
        $count = $array[0]['count(*)'];
        if (empty($result)) {
            
            Db::query("insert into ym_petDiary_notes_upvote values(null,'$note_id','$user_id',1)");
            if ($count == 0) {
                Db::query("insert into ym_notes_upvotecount values(null,'$note_id','$count' + 1)");
                return $this->returnmsg(200,"点赞成功");
            }else{
                Db::query("update ym_notes_upvotecount set upvoteCount = '$count' + 1 where note_id = '$note_id'");
                return $this->returnmsg(200,"点赞成功");
            }
        }else{
            $upvote = $result[0]['note_upvote'];
            if ($count != 0) {
                if ($upvote == 0) {
                    Db::query("update ym_petDiary_notes_upvote set note_upvote = 1 where user_id = '$user_id' and note_id = '$note_id'");
                    Db::query("update ym_notes_upvotecount set upvoteCount = 1 where note_id = '$note_id'");
                    return $this->returnmsg(200,"点赞成功");

                }else{
                    Db::query("delete from  ym_petDiary_notes_upvote where user_id = '$user_id' and note_id = '$note_id'");
                    Db::query("update ym_notes_upvotecount set upvoteCount = '$count' - 1 where note_id = '$note_id'");
                    return $this->returnmsg(201,"取消点赞成功");
                }   
            }else{
                    Db::query("update ym_petDiary_notes_upvote set note_upvote = 1 where user_id = '$user_id' and note_id = '$note_id'");
                    
                    Db::query("update ym_notes_upvotecount set upvoteCount = '$count + 1' where note_id = '$note_id'");
                    return $this->returnmsg(200,"点赞成功");
            }
        }
    }


    //评论文章
    public function notes_cmmt($note_id,$user_id,$cmmt_content){

        Db::query("insert into ym_petDiary_cmmt values(null,'$note_id','$user_id','$cmmt_content',now())");
        $result = Db::table('user_info')->alias('a')->join('ym_petDiary_cmmt b','a.user_id = b.user_id')->field(['a.user_name','a.user_icon','b.cmmt_content','b.create_time'])->where('a.user_id',$user_id)->where('b.note_id',$note_id)->select();

        return $this->returnmsg(200,'发表评论成功',$result);
    }

    //删除文章评论11-10
    public function delete_petDiary_note_cmmt($note_id,$cmmt_id){
        Db::query("delete from ym_petDiary_cmmt where note_id = '$note_id' and cmmt_id = '$cmmt_id'");
        $result = Db::query("select *from ym_petDiary_cmmt where note_id = '$note_id' and cmmt_id = '$cmmt_id'");
        if (empty($result)) {
            Db::query("delete from ym_petDiary_cmmt_upvote where note_id = '$note_id' and cmmt_id = '$cmmt_id'");
            Db::query("delete from ym_petDiary_cmmt_upvoteCount where note_id = '$note_id' and cmmt_id = '$cmmt_id'");
            return $this->returnmsg(200,"删除成功");
        }else{
            return $this->returnmsg(400,"删除失败");
        }
    }

    //文章评论取消点赞
    public function notes_cmmt_upvote($user_id,$note_id,$cmmt_id) {
        
        $result = Db::query("select cmmt_upvote from ym_petDiary_cmmt_upvote where user_id = '$user_id' and note_id = '$note_id' and cmmt_id = '$cmmt_id'");
        $array = Db::query(" select count(*)from ym_petDiary_cmmt_upvote where note_id = '$note_id' and cmmt_id = '$cmmt_id'");
        $count = $array[0]['count(*)'];
        if (empty($result)) {
            
            Db::query("insert into ym_petDiary_cmmt_upvote values(null,'$cmmt_id','$note_id','$user_id',1)");
            if ($count == 0) {
                Db::query("insert into ym_petDiary_cmmt_upvoteCount values(null,'$cmmt_id','$note_id','$count' + 1)");
                return $this->returnmsg(200,"点赞成功");
            }else{
                Db::query("update ym_petDiary_cmmt_upvoteCount set cmmt_upvoteCount = '$count' + 1 where note_id = '$note_id' and cmmt_id = '$cmmt_id'");
                return $this->returnmsg(200,"点赞成功");
            }
        }else{
            $cmmt_upvote = $result[0]['cmmt_upvote'];
            if ($count != 0) {
                if ($cmmt_upvote == 0) {
                    Db::query("update ym_petDiary_cmmt_upvote set cmmt_upvote = 1  where note_id = '$note_id' and cmmt_id = '$cmmt_id'");
                    
                    Db::query("update ym_petDiary_cmmt_upvoteCount set cmmt_upvoteCount = 1 where note_id = '$note_id' and cmmt_id = '$cmmt_id'");
                    return $this->returnmsg(200,"点赞成功");

                }else{
                    Db::query("delete from ym_petDiary_cmmt_upvote  where note_id = '$note_id' and cmmt_id = '$cmmt_id' and user_id = '$user_id'");
                    Db::query("update ym_petDiary_cmmt_upvoteCount set cmmt_upvoteCount = '$count' - 1 where note_id = '$note_id' and cmmt_id = '$cmmt_id'");
                    return $this->returnmsg(200,"取消点赞成功");
                }   
            }else{
                 Db::query("update ym_petDiary_cmmt_upvote set cmmt_upvote = 1 where note_id = '$note_id' and cmmt_id = '$cmmt_id'");
                    echo "<br />c".$count;
                    Db::query("update ym_petDiary_cmmt_upvoteCount set cmmt_upvoteCount = '$count' + 1 where note_id = '$note_id' and cmmt_id = '$cmmt_id'");
                    return $this->returnmsg(200,"点赞成功");
            }
        }
    }

    //收藏文章
    public function notes_collection($note_id,$user_id){
        $result = Db::query("select * from ym_petDiary_collection where note_id = '$note_id' and user_id = '$user_id'");
        if (empty($result)) { // 如果用户没有收藏
            Db::query("insert into ym_petDiary_collection values(null,'$user_id','$note_id',now())");
            return $this->returnmsg(200,"收藏成功");
        }else{// 如果用户收藏了，就是取消收藏
            Db::query("delete from ym_petDiary_collection where note_id = '$note_id' and user_id = '$user_id'");
            return $this->returnmsg(201,"取消收藏成功");
        }
    }

    //领养
    public function adopt_pet_update($adopt_addr,$adopt_pet_name,$adopt_pet_gender,$adopt_pet_age,$adopt_pet_weight,$adopt_pet_kind,$adopt_pet_Sterilization,$adopt_pet_vaccine){

        $file = Request::instance()->file('adopt_pet_icon');

        $info = $file->move(ROOT_PATH . 'public' . DS. 'uploads'.DS.'adopt_pet_icon');
        if ($info) {
            $icon_path = '/uploads/adopt_pet_icon/' . $info->getSaveName();
            $icon_path = str_replace('\\', '/', $icon_path);

            $data = ['adopt_addr'=>$adopt_addr,'adopt_pet_name'=>$adopt_pet_name,'adopt_pet_gender'=>$adopt_pet_gender,'adopt_pet_age'=>$adopt_pet_age,'adopt_pet_weight'=>$adopt_pet_weight,'adopt_pet_kind'=>$adopt_pet_kind,'adopt_pet_Sterilization'=>$adopt_pet_Sterilization,'adopt_pet_vaccine'=>$adopt_pet_vaccine,'adopt_pet_icon'=>$icon_path];

            $adopt_id = Db::table('ym_adopt')->insertGetId($data);

            Db::query("insert into ym_adopt_pet_hungry values(null,'$adopt_id',100)");

            return $this->returnmsg(200,"添加信息成功");
    }
}
    //返回地区
    public function show_adopt_addr(){
        $address = Db::query("select distinct adopt_addr from ym_adopt order by adopt_id asc");
        
        return $this->returnmsg(200,'地区',$address);
    }

    //领养模块-喂养
    public function adopt_hungry_level($user_id,$adopt_id,$food_count){
        $now_time = date('Y-m-d h:i:s');
        
        $hungry = Db::query("select pet_hungry_level from ym_adopt_pet_hungry where adopt_id = '$adopt_id'");
        $hungry_level = $hungry[0]['pet_hungry_level'];
        Db::query("update ym_adopt_pet_hungry set pet_hungry_level = '$hungry_level' + '$food_count' where adopt_id = '$adopt_id'");
        $result = Db::query("select * from ym_adopt_feed_pet where user_id = '$user_id' and adopt_id = '$adopt_id'");
        if (!empty($result)) {
            $t = Db::query("select feed_time from ym_adopt_feed_pet where user_id = '$user_id' and adopt_id = '$adopt_id'");
            $feed_time = $t[0]['feed_time'];
            $timediff = (strtotime($now_time) - strtotime($feed_time))/86400;
            if ($timediff > 1 && $timediff < 2) {
                // echo 1;
                $day = Db::query("select continue_day from ym_adopt_feed_pet where user_id = '$user_id' and adopt_id = '$adopt_id'");
                $continue_day = $day[0]['continue_day'];
                Db::query("update ym_adopt_feed_pet set feed_time = '$now_time',continue_day = '$continue_day' + 1 where user_id = '$user_id' and adopt_id = '$adopt_id'");
            }elseif ($timediff < 1) {
                $day = Db::query("select continue_day from ym_adopt_feed_pet where user_id = '$user_id' and adopt_id = '$adopt_id'");
                $continue_day = $day[0]['continue_day'];
                Db::query("update ym_adopt_feed_pet set feed_time = '$now_time',continue_day = '$continue_day' where user_id = '$user_id' and adopt_id = '$adopt_id'");
            }else{
                Db::query("update ym_adopt_feed_pet set feed_time = '$now_time',continue_day = 1 where user_id = '$user_id' and adopt_id = '$adopt_id'");
            }
        }else{
            Db::query("insert into ym_adopt_feed_pet values(null,'$adopt_id','$user_id',now(),default)");
            return $this->returnmsg(201,'第一次喂养成功',1);
        }
        $day = Db::query("select continue_day from ym_adopt_feed_pet where user_id = '$user_id' and adopt_id = '$adopt_id'");
        $continue_days = $day[0]['continue_day'];
        return $this->returnmsg(200,'喂养成功',$continue_days);
    }

    //判断宠物饱饥状态12-1
    public function judgement_adopt_hungry_level($user_id,$adopt_id,$food_count){
        $result = Db::query("select pet_hungry_level from ym_adopt_pet_hungry where adopt_id = '$adopt_id'");
        $association = Db::query("select association_id from ym_adopt_pet_association where adopt_id = '$adopt_id'");
        $association_id = $association[0]['association_id'];
        $pet_hungry_level = $result[0]['pet_hungry_level'];

        if ($pet_hungry_level == 10000) {
            return $this->returnmsg(401,"宠物好饱哦,待会再来吧");
        }elseif ( $pet_hungry_level + $food_count > 10000) {
            return $this->returnmsg(403,"土豪，留着下次喂养吧！！");
        }else{
            $this->adopt_user_reward($user_id,$association_id,$food_count);
            $this->adopt_hungry_level($user_id,$adopt_id,$food_count);
        }
    }

    //喂养者,减少宠粮
    public function adopt_user_reward($reward_user_id,$association_id,$food_count){
        $result = Db::query("select association_pet_food from ym_adopt_association where association_id = '$association_id'");
        $association_pet_food = $result[0]['pet_food'];
        $pet_food = $this->get_pet_food($reward_user_id);
        if ($pet_food >= $food_count) {
            Db::query("update ym_pet_food set pet_food = '$pet_food' - '$food_count' where user_id = '$reward_user_id'");
            // 慈善机构加宠粮,被喂养
            Db::query("update ym_adopt_association set association_pet_food = association_pet_food + '$food_count' where association_id = '$association_id'");
        }else{
            return $this->returnmsg(402,'宠粮余额不足,请充值');
        }  
    }
    
    //按地区显示宠物信息
    public function show_adopt_pet($adopt_addr,$pageno){
        
        $startno = $pageno * 20;
        $result = Db::table('ym_adopt_pet_association')->alias('a')->join('ym_adopt b','a.adopt_id = b.adopt_id')->join('ym_adopt_association c','a.association_id = c.association_id')->field(['b.adopt_id','b.adopt_pet_name','b.adopt_pet_Sterilization','b.adopt_pet_vaccine','b.adopt_pet_icon','c.association_name','c.association_icon'])->where('b.adopt_addr',$adopt_addr)->limit($startno,20)->select();
        
        return $this->returnmsg(200,'领养宠物信息',$result);
  }

    //查看连续喂养了多少天
    public function continue_day($day_list){
        // $time = date('Y-m-d');
        $continue_day = 1 ;//连续天数
        $length = count($day_list);

        if($length >= 1){      
         for ($i=0; $i<=count($day_list); $i++){
            $timediff = strtotime(date('Y-m-d')) - strtotime($day_list[$i]['feed_time']);
                    
            if((abs($timediff) / 86400) == $i){

                $continue_day = $i+1;        
              } else {        
                   break;        
               }      
            }  
         }      
         return $continue_day;    //输出连续几天
    }

    // 显示宠物详细信息
    public function show_adopt_petinfo($user_id,$adopt_id){
        $now_time = date('Y-m-d H:i:s');
        
        $day = Db::query("select continue_day from ym_adopt_feed_pet where user_id = '$user_id' and adopt_id = '$adopt_id'");
        $continue_days = $day[0]['continue_day'];
        $t = Db::query("select feed_time from ym_adopt_feed_pet where user_id = '$user_id' and adopt_id = '$adopt_id'");
        $feed_time = $t[0]['feed_time'];
        $timediff = (strtotime($now_time) - strtotime($feed_time))/86400;
        $pet_img = Db::query("select img_url from ym_adopt_pet_img where adopt_id = '$adopt_id'");

        $result = Db::query("select a.pet_desc,a.join_time,b.adopt_pet_name,b.adopt_pet_age,b.adopt_pet_gender,b.adopt_pet_weight,b.adopt_pet_kind,b.adopt_pet_Sterilization,b.adopt_pet_vaccine,b.adopt_pet_icon,c.association_name,c.association_icon,d.pet_hungry_level from ym_adopt_pet_association as a join ym_adopt as b on a.adopt_id = b.adopt_id join ym_adopt_association as c on a.association_id = c.association_id join ym_adopt_pet_hungry as d on a.adopt_id = d.adopt_id where a.adopt_id = '$adopt_id'");
        if ($timediff > 2) {
            
            Db::query("update ym_adopt_feed_pet set continue_day = 0 where user_id = '$user_id' and adopt_id = '$adopt_id'");
            $day = Db::query("select continue_day from ym_adopt_feed_pet where user_id = '$user_id' and adopt_id = '$adopt_id'");
            $continue_day = $day[0]['continue_day'];
            $arr = array('img' => $pet_img , 'adopt_pet_info' => $result,'continue_day'=>$continue_day);
            return $this->returnmsg(200,'领养宠物详细信息',$arr);
        }else{
            $arr = array('img' => $pet_img , 'adopt_pet_info' => $result,'continue_day'=>$continue_days);
            return $this->returnmsg(200,'领养宠物详细信息',$arr);
        }
    }  

    //申请领养
    public function adoption_application($nick_name,$gender,$brith,$ID,$phone,$email,$organization,$address,$Living_environment,$adpotion_remark){
        switch ($gender) {
            case '男':
                $gender = 0;
                break;
            case '女 ':
                $gender = 1;
                break;
        }
        switch ($Living_environment) {

            case '产权房':
                $Living_environment = 0;
                break;
            case '独立租房':
                $Living_environment = 1;
                break;
            case '合租房 ':
                $Living_environment = 2;
                break;
        }
        $positive_file = Request::instance()->file('ID_positive_picture');
        //身份证反面
        $opposite_file = Request::instance()->file('ID_opposite_picture');
        $house_file = Request::instance()->file('housing_contract_picture');
        // 移动到框架应用根目录/public/uploads/ 目录下
        // $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
        $positive_info = $positive_file->move(ROOT_PATH . 'public' . DS. 'uploads'.DS.'adoption_ID_positive_picture');
        $opposite_info = $opposite_file->move(ROOT_PATH . 'public' . DS. 'uploads'.DS.'adoption_ID_opposite_picture');
        $housing_info = $house_file->move(ROOT_PATH . 'public' . DS. 'uploads'.DS.'housing_contract_picture');
        //$res = db('user')->where('user_id', $data['user_id'])->setField('user_icon', $head_img_path);
        if($opposite_info && $housing_info && $positive_info){
            // 成功上传后 获取上传信息
            // 输出 jpg
            $positive_path = '/uploads/adoption_ID_positive_picture/' . $positive_info->getSaveName();
            $opposite_path = '/uploads/adoption_ID_opposite_picture/' . $opposite_info->getSaveName();
            $housing_contract_path = '/uploads/housing_contract_picture/' . $housing_info->getSaveName();
            $positive_path = str_replace('\\', '/', $positive_path);
            $opposite_path = str_replace('\\', '/', $opposite_path);
            $housing_contract_path = str_replace('\\', '/', $housing_contract_path);
            if (!empty($adpotion_remark)) {
                Db::query("insert into ym_adoption_personInfo values(null,'$nick_name','$gender','$brith','$ID','$phone','$email','$organization','$address','$Living_environment','$positive_path','$opposite_path','$housing_contract_path','$adpotion_remark')");
                return $this->returnmsg(200,"申请成功，请等待审核");
            }else{
                Db::query("insert into ym_adoption_personInfo values(null,'$nick_name','$gender','$brith','$ID','$phone','$email','$organization','$address','$Living_environment','$positive_path','$opposite_path','$housing_contract_path',default)");
                return $this->returnmsg(200,"申请成功，请等待审核");
            }
        }
    }

    //申请试养
    public function try_adoption_application($nick_name,$gender,$brith,$ID,$phone,$email,$organization,$address,$Living_environment,$adpotion_remark){
        switch ($gender) {
            case '男':
                $gender = 0;
                break;
            case '女 ':
                $gender = 1;
                break;
        }
        switch ($Living_environment) {

            case '产权房':
                $Living_environment = 0;
                break;
            case '独立租房':
                $Living_environment = 1;
                break;
            case '合租房 ':
                $Living_environment = 2;
                break;
        }

        $positive_file = Request::instance()->file('try_ID_positive_picture');
        //身份证反面
        $opposite_file = Request::instance()->file('try_ID_opposite_picture');
        $positive_info = $positive_file->move(ROOT_PATH . 'public' . DS. 'uploads'.DS.'try_adoption_ID_positive_picture');
        $opposite_info = $opposite_file->move(ROOT_PATH . 'public' . DS. 'uploads'.DS.'try_adoption_ID_opposite_picture');
        if($opposite_file && $positive_info){
            // 成功上传后 获取上传信息
            // 输出 jpg
            $positive_path = '/uploads/try_adoption_ID_positive_picture/' . $positive_info->getSaveName();
            $opposite_path = '/uploads/try_adoption_ID_opposite_picture/' . $opposite_info->getSaveName();
            $positive_path = str_replace('\\', '/', $positive_path);
            $opposite_path = str_replace('\\', '/', $opposite_path);
            if (!empty($adpotion_remark)) {
                Db::query("insert into ym_try_adoption_personInfo values(null,'$nick_name','$gender','$brith','$ID','$phone','$email','$organization','$address','$Living_environment','$positive_path','$opposite_path','$adpotion_remark')");
                return $this->returnmsg(200,"申请成功，请等待审核");
            }else{
                Db::query("insert into ym_try_adoption_personInfo values(null,'$nick_name','$gender','$brith','$ID','$phone','$email','$organization','$address','$Living_environment','$positive_path','$opposite_path',default)");
                return $this->returnmsg(200,"申请成功，请等待审核");
            }
        }    
    }

    public function get_adopt_pet_food($user_id){
        $result = Db::query("select pet_food from ym_pet_food where user_id = '$user_id'");
        $pet_food = $result[0]['pet_food'];
        $arr = ['pet_food'=>$pet_food];
        return json($arr);
    }

    //拿到该用户的宠粮数
    public function get_pet_food($user_id){
        $result = Db::query("select pet_food from ym_pet_food where user_id = '$user_id'");
        $pet_food = $result[0]['pet_food'];
        return $pet_food;
    }

/**
 * 打赏
 * @param $reward_user_id 打赏者id
 * @param $bereward_user_id 被打赏者id
 * @param $food_count 打赏宠粮数
 * @return json
 */
    //打赏者 -
    public function user_reward($reward_user_id,$bereward_user_id,$food_count,$id,$type){
        // $result = Db::query("select pet_food from user_info where user_id = '$reward_user_id'");
        // $pet_food = $result[0]['pet_food'];
        $time = date('Y-m-d H:i:s');
        $pet_food = $this->get_pet_food($reward_user_id);
        if ($pet_food >= $food_count) {
            Db::query("update ym_pet_food set pet_food = '$pet_food' - '$food_count' where user_id = '$reward_user_id'");
            $message_data = ['be_user_id'=>$bereward_user_id,'user_id'=>$reward_user_id,'message_type'=>5,'create_time'=>$time];
            $m_id = Db::table('ym_message')->insertGetId($message_data);
            if ($type == 0) {//随手拍
                $post_id = $id;
                $img = Db::query("select img_url from ym_snapshot_img where post_id = '$post_id' limit 1");
                $img_url = $img[0]['img_url'];
                $reward_data = ['m_id'=>$m_id,'module_type'=>0,'id'=>$post_id,'food_count'=>$food_count,'img_url'=>$img_url];
                $m_reward_id = Db::table('ym_message_reward')->insertGetId($reward_data);
                // Db::query("insert into ym_message_reward_post values(null,'$m_reward_id','$post_id','$food_count','$img_url')");
            }elseif ($type == 1) {//个人动态
                $dynamic_id = $id;
                $img = Db::query("select img_url from ym_user_dynamic_img where dynamic_id = '$dynamic_id' limit 1");
                $img_url = $img[0]['img_url'];
                $reward_data = ['m_id'=>$m_id,'module_type'=>1,'id'=>$dynamic_id,'food_count'=>$food_count,'img_url'=>$img_url];
                $m_reward_id = Db::table('ym_message_reward')->insertGetId($reward_data);
            }
            
            $user_name = Db::query("select user_name from user_info where user_id = '$reward_user_id'");
            $name = $user_name[0]['user_name'];

            // $message = '关注了你';
            $bereward_user_id = strval($bereward_user_id);
            $this->push($bereward_user_id,$name.'打赏了你'.$food_count.'克宠粮');
            $this->user_be_rewarded($bereward_user_id,$food_count);
        }else{
            return $this->returnmsg(402,'宠粮余额不足,请充值');
        }  
    }

    //用户加宠粮，被打赏 +
    public function user_be_rewarded($bereward_user_id,$food_count){
        
        $pet_food = $this->get_pet_food($bereward_user_id);

        Db::query("update ym_pet_food set pet_food = '$pet_food' + '$food_count' where user_id = '$bereward_user_id'");
        return $this->returnmsg(200,"打赏成功");
    }



/**
 * 寄养
 * @param $user_id 寄养用户id 当前登入用户
 * @param $be_fosterage_user_id 收养用户id
 * @param $fosterage_name 真实姓名
 * @param $fosterage_phone 联系方式
 * @param $fosterage_reason 寄养原因
 * @param $fosterage_matters_need_attention 寄养注意事项
 * @param $fosterage_start_time 寄养开始时间
 * @param $fosterage_start_time 寄养结束时间
 * @param fosterage_img 宠物图片
 * @return int
 */
    public function fosterage_form($user_id,$be_fosterage_user_id,$fosterage_name,$fosterage_phone,$fosterage_reason,$fosterage_matters_need_attention,$fosterage_start_time,$fosterage_end_time){
        $time = date('Y-m-d H:i:s');
        $files = Request::instance()->file('fosterage_img');
        // 移动到框架应用根目录/public/uploads/ 目录下
        // $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
        $info = $files->move(ROOT_PATH . 'public' . DS. 'uploads'.DS.'fosterage_img');
        //$res = db('user')->where('user_id', $data['user_id'])->setField('user_icon', $head_img_path);
        if($info){
            // 成功上传后 获取上传信息
            // 输出 jpg
            $path = '/uploads/fosterage_img/' . $info->getSaveName();
            $path = str_replace('\\', '/', $path);

            $data = ['user_id' =>$user_id,'be_fosterage_user_id'=>$be_fosterage_user_id,'fosterage_name' =>$fosterage_name,'fosterage_phone' =>$fosterage_phone,'fosterage_reason' =>$fosterage_reason,'fosterage_matters_need_attention' =>$fosterage_matters_need_attention,'fosterage_start_time' =>$fosterage_start_time,'fosterage_end_time' =>$fosterage_end_time];
            
            $fosterage_id = Db::table('ym_fosterage')->insertGetId($data);
            
            $img_data = ['fosterage_img_id' => null,'fosterage_id' =>$fosterage_id,'fosterage_img' =>$path];
            Db::table('ym_fosterage_img')->insert($img_data);

            $message_data = ['be_user_id'=>$be_fosterage_user_id,'user_id'=>$user_id,'message_type'=>6,'create_time'=>$time];
            $m_id = Db::table('ym_message')->insertGetId($message_data);
            $fosterage_data = ['m_id'=>$m_id,'fosterage_id'=>$fosterage_id];
            $m_fosterage_id = Db::table('ym_message_fosterage')->insertGetId($fosterage_data);

            $user_name = Db::query("select user_name from user_info  where user_id = '$user_id'");
            $name = $user_name[0]['user_name'];

            // $message = '关注了你';
            $be_fosterage_user_id = strval($be_fosterage_user_id);
            $this->push($be_fosterage_user_id,$name.'想要将他的宠物寄养给你');
            return $this->returnmsg(200,'寄养表填写成功');
        }
    }

    //显示寄养
    public function show_fosterage_form($fosterage_id){
        $result = Db::table('ym_fosterage')->alias('a')->join('ym_fosterage_img b','a.fosterage_id = b.fosterage_id')->join('user_info c','a.user_id = c.user_id')->field(['c.user_name','c.user_icon','a.user_id','a.fosterage_id','a.fosterage_name','a.fosterage_phone','a.fosterage_reason','a.fosterage_matters_need_attention','fosterage_start_time','fosterage_end_time','a.fosterage_status','b.fosterage_img'])->where('a.fosterage_id',$fosterage_id)->select();
        return $this->returnmsg(200,"寄养表信息",$result);
    }

    //同意或者不同意寄养
    public function fosterage_agree_or_refuse($fosterage_agree,$reason,$user_id,$fosterage_id){
        $time = date('Y-m-d H:i:s');
        $be_id = Db::query("select user_id from ym_fosterage where fosterage_id = '$fosterage_id'");
        $be_user_id = $be_id[0]['user_id'];
        $user_name = Db::query("select user_name from user_info  where user_id = '$user_id'");
        $name = $user_name[0]['user_name'];
        if ($fosterage_agree == 0) {//拒绝收养
            $refuse_data = ['fosterage_id'=>$fosterage_id,'user_id'=>$user_id,'fosterage_agree'=>$fosterage_agree,'fosterage_refuse_reason'=>$reason];
            Db::table('ym_fosterage_agree_or_refuse')->insert($refuse_data);
            Db::query("update ym_fosterage set fosterage_status = 0 where fosterage_id = '$fosterage_id'");
            //message
            $message_data = ['be_user_id'=>$be_user_id,'user_id'=>$user_id,'message_type'=>7,'create_time'=>$time];
            $m_id = Db::table('ym_message')->insertGetId($message_data);
            $fosterage_data = ['m_id'=>$m_id,'refuse_reason'=>$reason,'fosterage_id'=>$fosterage_id];
            $m_fosterage_id = Db::table('ym_message_fosterage_agree_or_not')->insertGetId($fosterage_data);

            $be_user_id = strval($be_user_id);
            $this->push($be_user_id,$name.'拒绝收养的你宠物,原因:'.$reason);
            return $this->returnmsg(200,"拒绝收养",$refuse_data);
        }else{
            $agree_data = ['fosterage_id'=>$fosterage_id,'user_id'=>$user_id,'fosterage_agree'=>$fosterage_agree];
            Db::table('ym_fosterage_agree_or_refuse')->insert($agree_data);

            Db::query("update ym_fosterage set fosterage_status = 1 where fosterage_id = '$fosterage_id'");

            //message
            $message_data = ['be_user_id'=>$be_user_id,'user_id'=>$user_id,'message_type'=>7,'create_time'=>$time];
            $m_id = Db::table('ym_message')->insertGetId($message_data);
            $fosterage_data = ['m_id'=>$m_id,'fosterage_id'=>$fosterage_id];
            $m_fosterage_id = Db::table('ym_message_fosterage_agree_or_not')->insertGetId($fosterage_data);

            $be_user_id = strval($be_user_id);
            $this->push($be_user_id,$name.'同意收养的你宠物');
            return $this->returnmsg(200,"同意收养",$agree_data);
        }
    }

    //用户是否同意接受寄养
    public function fosterage_or_not($user_id,$fosterage_or_not){
        if ($fosterage_or_not == 1) {
            Db::query("update user_info set fosterage_or_not = 1 where user_id = '$user_id'");
            return $this->returnmsg(200,'已开启');
        }else{
            Db::query("update user_info set fosterage_or_not = 0 where user_id = '$user_id'");
            return $this->returnmsg(200,'已关闭');
        } 
    }

    //返回是否同意寄养宠物
    public function judgement_fosterage($user_id){
        $result = Db::query("select fosterage_or_not from user_info where user_id = '$user_id'");
        return json($result[0]);
    }

    //GPS
    
    //是否同意共享自己的宠物
    public function appoint_agree_or_not($user_id,$type){
        if ($type == 1) {
            Db::query("update user_info set share_pet_agree_or_not = 1 where user_id = '$user_id'");
            return $this->returnmsg(200,'已开启');
        }else{
            Db::query("update user_info set share_pet_agree_or_not = 0 where user_id = '$user_id'");
            return $this->returnmsg(200,'已关闭');
        }
    }

    //返回是否同意共享宠物
    public function judgement_appoint($user_id){
        $result = Db::query("select share_pet_agree_or_not from user_info where user_id = '$user_id'");
        return json($result[0]);
    }

    //GPS返回周围$distance范围内的用户
    public function GetRange($latitude,$longitude,$distance){
         
            $m = Db::connect("db_mongo")->table("yunmiao_location")->where(['loc' => ['near',[floatval($longitude),floatval($latitude),intval($distance)*1000]]] )->select();
            
            foreach ($m as $k =>$v) {
                $user_id = $m[$k]['user_id'];
                
                $result = Db::query("select a.pet_icon,b.pet_type,b.share_pet_agree_or_not from ym_pet as a join user_info as b on a.user_id = b.user_id  where a.user_id = '$user_id'");
                if ($result[0]['share_pet_agree_or_not'] == 1) {
                    $m[$k]['pet_info'] = $result[0];
                }else{
                    array_splice($m,$k,1,'null');
                }
                
            }
            
            return json($m);
    }

    //附近的人
    public function nearby_users($latitude,$longitude,$distance,$pageno){
        $pagesize = 20;
        $startno = $pageno *$pagesize;

        $m = Db::connect("db_mongo")->table("yunmiao_location")->where(['loc' => ['near',[floatval($longitude),floatval($latitude),intval($distance)*1000]]])->limit($startno,$pagesize)->order('distances','asc')->select();
        
        

        foreach ($m as $k =>$v) {
            // $user_id = $v['user_id'];
            $user_id = $m[$k]['user_id'];
            $longitude1 =  $m[$k]['loc']['coordinates'][0];
            $latitude1 =  $m[$k]['loc']['coordinates'][1];
            
            $result = Db::query("select user_id,user_name,user_icon,user_desc from user_info where user_id = '$user_id'");
            
            
            $distances = $this->calculate_distance($latitude, $longitude, $latitude1, $longitude1)*1000;
            if ($distances < 100) {
                $distances = 100;
            }
            if (!empty($result)) {
                $arr[] = ['user_info'=>$result[0],'distances'=>$distances];
            }
            
        }
        if (!empty($arr)) {
            $user = $this->f_order($arr,'distances',1);
            return $this->returnmsg(200,'附近的人',$user);
        }else{
            return $this->returnmsg(200,'附近没有用户');
        }
        
    }

    public function f_order($arr,$field,$sort){
        $order = array();
        foreach($arr as $kay => $value){
            $order[] = $value[$field];
        }
        if($sort==1){
            array_multisort($order,SORT_ASC,$arr);
        }else{
            array_multisort($order,SORT_DESC,$arr);
        }
        return $arr;
    }

 
    public function get_petInfo($user_id,$fP1Lat, $fP1Lon, $fP2Lat, $fP2Lon){

        $result = Db::query("select a.pet_id,a.user_id,a.pet_name,a.pet_brith,a.pet_kind,a.pet_gender,a.pet_icon,b.user_icon,b.fans_count,b.fosterage_or_not from ym_pet as a join user_info as b on a.user_id = b.user_id  where a.user_id = '$user_id' and a.permisstion_to_access = 1");
        $pet_id = array();
        foreach ($result as $key => $value) {
            $pet_id[] = $result[$key]['pet_id'];
            $lengh = count($pet_id);
            for ($i=0; $i < $lengh ; $i++) {
                $count = Db::query("select count(1) as count from ym_pet_appointment where pet_id = '$pet_id[$i]'");
                $result[$key]['appointment_count'] = $count[0]['count'];

                if ($count[0]['count'] <= 5) {
                    $user_icons = Db::table('ym_pet_appointment')->field('user_icon')->where('owned_user_id',$user_id)->where('pet_id',$pet_id[$i])->select();
                    $user_icon = $user_icons[$i]['user_icon'];
                }else{
                    $user_icons = Db::table('ym_pet_appointment')->field('user_icon')->where('owned_user_id',$user_id)->where('pet_id',$pet_id[$i])->limit(5)->select();

                }
            }
            $result[$key]['user_icons'] = $user_icons;
        }
        
        $distance = $this->calculate_distance($fP1Lat, $fP1Lon, $fP2Lat, $fP2Lon);
        $res = ['pet_info'=>$result,'distance'=>$distance];
        return $this->returnmsg(200,'petInfo',$res);
    }


    public function judgement_pet_food($user_id){
        $res = Db::table('ym_pet_food')->field('pet_food')->where('user_id',$user_id)->select();
        $pet_food = $res[0]['pet_food'];

        if ($pet_food >=70) {
            return $this->returnmsg(200,'可以约宠');
        }else{
            return $this->returnmsg(401,'宠粮余额不足以约宠');
        }
    }

    public function appointment_pet($user_id,$pet_id,$number_of_people,$appointment_location,$appointment_remarks,$appointment_time){
        $time = date('Y-m-d H:i:s');
        $owned = Db::table('ym_pet')->field('user_id')->where('pet_id',$pet_id)->select();
        $owned_user_id = $owned[0]['user_id'];
        $result = Db::table('user_info')->field('user_icon')->where('user_id',$user_id)->select();
        $user_icon = $result[0]['user_icon'];
        if (!empty($appointment_remarks)) {
            $data = ['user_id'=>$user_id,'pet_id'=>$pet_id,'owned_user_id'=>$owned_user_id,'user_icon'=>$user_icon,'number_of_people'=>$number_of_people,'appointment_location'=>$appointment_location,'appointment_remarks'=>$appointment_remarks,'appointment_time'=>$appointment_time];

            $appointment_id = Db::table('ym_pet_appointment')->insertGetId($data);
            
        }else{
            $data = ['user_id'=>$user_id,'pet_id'=>$pet_id,'owned_user_id'=>$owned_user_id,'user_icon'=>$user_icon,'number_of_people'=>$number_of_people,'appointment_location'=>$appointment_location,'appointment_time'=>$appointment_time];
            $appointment_id = Db::table('ym_pet_appointment')->insertGetId($data);
        }
        $message_data = ['be_user_id'=>$owned_user_id,'user_id'=>$user_id,'message_type'=>1,'create_time'=>$time];
        $m_id = Db::table('ym_message')->insertGetId($message_data);
        $appointment_data = ['m_id'=>$m_id,'appointment_id'=>$appointment_id];
        $m_appointment_id = Db::table('ym_message_appointment')->insertGetId($appointment_data);

        $user_name = Db::query("select user_name from user_info where user_id = '$user_id'");
        $name = $user_name[0]['user_name'];
        $pet = Db::query("select pet_name from ym_pet where pet_id = '$pet_id'");
        $pet_name = $pet[0]['pet_name'];

        $owned_user_id = strval($owned_user_id);
        $this->push($owned_user_id,$name.'约了你的宠物:'.$pet_name);
        return $this->returnmsg(200,'成功');
    }


    public function show_appointment($appointment_id){
        $result = Db::table('ym_pet_appointment')->alias('a')->join('ym_pet b','a.pet_id = b.pet_id')->join('user_info c','a.user_id = c.user_id')->field(['c.user_name','c.user_icon','b.pet_icon','a.user_id','a.appointment_id','a.appointment_status','a.number_of_people','a.appointment_time','a.appointment_location'])->where('a.appointment_id',$appointment_id)->select();
        return $this->returnmsg(200,"寄养表信息",$result);
    }


    public function agree_appointment_pet($appointment_agree,$reason,$user_id,$appointment_id){
        
        $time = date('Y-m-d H:i:s');
        $be_id = Db::query("select user_id from ym_pet_appointment where appointment_id = '$appointment_id'");
        $be_user_id = $be_id[0]['user_id'];//接受消息方，约宠方
        $user_name = Db::query("select user_name from user_info  where user_id = '$user_id'");
        $name = $user_name[0]['user_name'];
        if ($appointment_agree == 0) {//拒绝收养
            $refuse_data = ['appointment_id'=>$appointment_id,'user_id'=>$user_id,'appointment_agree'=>$appointment_agree,'refuse_reason'=>$reason];
            Db::table('ym_pet_appointment_agree_or_not')->insert($refuse_data);

            Db::query("update ym_pet_appointment set appointment_status = 0 where appointment_id = '$appointment_id'");

            //message
            $message_data = ['be_user_id'=>$be_user_id,'user_id'=>$user_id,'message_type'=>8,'create_time'=>$time];
            $m_id = Db::table('ym_message')->insertGetId($message_data);
            $appointment_data = ['m_id'=>$m_id,'refuse_reason'=>$reason,'appointment_id'=>$appointment_id];
            $m_appointment_id = Db::table('ym_message_appointment_agree_or_not')->insertGetId($appointment_data);

            $be_user_id = strval($be_user_id);
            $this->push($be_user_id,$name.'拒绝了你的约宠,原因:'.$reason);
            return $this->returnmsg(200,"拒绝收养",$refuse_data);
        }else{
            $agree_data = ['appointment_id'=>$appointment_id,'user_id'=>$user_id,'appointment_agree'=>$appointment_agree];
            Db::table('ym_pet_appointment_agree_or_not')->insert($agree_data);

            Db::query("update ym_pet_appointment set appointment_status = 1 where appointment_id = '$appointment_id'");

            //message
            $message_data = ['be_user_id'=>$be_user_id,'user_id'=>$user_id,'message_type'=>8,'create_time'=>$time];
            $m_id = Db::table('ym_message')->insertGetId($message_data);
            $appointment_data = ['m_id'=>$m_id,'appointment_id'=>$appointment_id];
            $m_appointment_id = Db::table('ym_message_appointment_agree_or_not')->insertGetId($appointment_data);

            $be_user_id = strval($be_user_id);
            $this->push($be_user_id,$name.'同意收养的你宠物');
            return $this->returnmsg(200,"同意收养",$agree_data);
        }
    }

    //插入用户  
    public function insert_map($latitude,$longitude,$user_id){ 
        
        $data = array(

            'user_id' => $user_id,
            'loc' => array(  
                    'type' => 'Point',  
                    'coordinates' => array(doubleval($longitude), doubleval($latitude))  
            )    
        );

        $result = Db::connect("db_mongo")->name("yunmiao_location")->where(['user_id' => $user_id])->select();
        
        if (!$result) {
            $m = Db::connect("db_mongo")->name("yunmiao_location")->insertGetId($data);
        }else{
            Db::connect("db_mongo")->name("yunmiao_location")->where(['user_id' => $user_id])->delete();
            $m = Db::connect("db_mongo")->name("yunmiao_location")->insertGetId($data);
            
        }
        
        if ($m) {
            return $this->returnmsg(200,'获取成功');
        }else{
            return $this->returnmsg(500,'获取失败');
        } 
    }

   public function calculate_distance($fP1Lat, $fP1Lon, $fP2Lat, $fP2Lon){
        $fEARTH_RADIUS = 6378137;
        //角度换算成弧度
        $fRadLon1 = deg2rad($fP1Lon);
        $fRadLon2 = deg2rad($fP2Lon);
        $fRadLat1 = deg2rad($fP1Lat);
        $fRadLat2 = deg2rad($fP2Lat);
        //计算经纬度的差值
        $fD1 = abs($fRadLat1 - $fRadLat2);
        $fD2 = abs($fRadLon1 - $fRadLon2);
        //距离计算
        $fP = pow(sin($fD1/2), 2) +
              cos($fRadLat1) * cos($fRadLat2) * pow(sin($fD2/2), 2);
        return round(floatval($fEARTH_RADIUS * 2 * asin(sqrt($fP))/1000),2);
    }

    public function get_ads_img(){
        $result = Db::query("select ads_img_url from ym_ads_img");
        $length = count($result);
        $img = [];
        for ($i=0; $i < $length; $i++) { 
            $img[] = $result[$i]['ads_img_url'];
        }
        return $img;
    }

}